Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  71] [ 2]  / answers: 1 / hits: 158157  / 11 Years ago, mon, july 22, 2013, 12:00:00

I have my JSON as follows



{DATA: [{id:11,name:ajax,subject:OR,mark:63},
{id:12,name:javascript,subject:OR,mark:63},
{id:13,name:jquery,subject:OR,mark:63},
{id:14,name:ajax,subject:OR,mark:63},
{id:15,name:jquery,subject:OR,mark:63},
{id:16,name:ajax,subject:OR,mark:63},
{id:20,name:ajax,subject:OR,mark:63}],COUNT:120}


Is there any good method to find out the distinct name from this JSON



Result javascript,jquery,ajax



I can do this using following methode



var arr=[''];
var j=0;
for (var i = 0; i < varjson.DATA.length; i++) {
if($.inArray(varjson.DATA[i][name],arr)<0){
arr[j]=varjson.DATA[i][name];
j++;
}
}


Is there any better method which gave me better performance?


More From » jquery

 Answers
3

I would use one Object and one Array, if you want to save some cycle:



var lookup = {};
var items = json.DATA;
var result = [];

for (var item, i = 0; item = items[i++];) {
var name = item.name;

if (!(name in lookup)) {
lookup[name] = 1;
result.push(name);
}
}


In this way you're basically avoiding the indexOf / inArray call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty.



Of course if you're fine with just an Object you can avoid the check and the result.push at all, and in case get the array using Object.keys(lookup), but it won't be faster than that.


[#76833] Saturday, July 20, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylie

Total Points: 121
Total Questions: 84
Total Answers: 91

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;