jquery - What is the correct way to select unique values for a single attribute out of a Javascript array of objects -


suppose have following javascript array of objects:

var odata = [     {field1 : "root", field2: "qqqqq", field3: "aaaaa", field4: "zzzzz"},     {field1 : "root", field2: "qqqqq", field3: "aaaaa", field4: "xxxxx"},     {field1 : "root", field2: "qqqqq", field3: "sssss", field4: "ccccc"},     {field1 : "root", field2: "wwwww", field3: "sssss", field4: "vvvvv"},     {field1 : "root", field2: "wwwww", field3: "ddddd", field4: "bbbbb"},     {field1 : "root", field2: "wwwww", field3: "ddddd", field4: "nnnnn"},     {field1 : "root", field2: "wwwww", field3: "fffff", field4: "mmmmm"} ]; 

what best performing way

  1. copy single attribute (field1, field2, field3, etc.) of array new array, and
  2. this resulting array contain list distinct values

i.e. resulting arrays be

var ofield1 = [     {field1 : "root"} ]  var ofield2 = [     {field2 : "qqqqq"},     {field2 : "wwwww"} ]  var ofield3 = [     {field3 : "aaaaa"},     {field3 : "sssss"},     {field3 : "ddddd"},     {field3 : "fffff"} ] 

(i have added 3 examples show try achieve. if can 1 attribute, can of course ;-) )

i can loop through array, , push unique values new arrays, or can clone array, remove unneeded attributes , slice make unique, these methods feel kinda 'dirty'

is there elegant yet good-performing way achieve above?

thanks in advance!

since you're using jquery:

$.unique(odata.map(function(x) { return x.field1; })) 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -