Selecting distinct values from a JSON
Underscore.js is great for this kind of thing. You can use _.countBy()
to get the counts per name
:
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}]
_.countBy(data, function(data) { return data.name; });
Gives:
{ajax: 4, javascript: 1, jquery: 2}
For an array of the keys just use _.keys()
_.keys(_.countBy(data, function(data) { return data.name; }));
Gives:
["ajax", "javascript", "jquery"]
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.