Assuming I have the following:
var array =
[
{\"name\":\"Joe\", \"age\":17},
{\"name\":\"Bob\", \"age\":17},
{\"name\":\"Carl\
The forEach
version of @travis-j's answer (helpful on modern browsers and Node JS world):
var unique = {};
var distinct = [];
array.forEach(function (x) {
if (!unique[x.age]) {
distinct.push(x.age);
unique[x.age] = true;
}
});
34% faster on Chrome v29.0.1547: http://jsperf.com/filter-versus-dictionary/3
And a generic solution that takes a mapper function (tad slower than direct map, but that's expected):
function uniqueBy(arr, fn) {
var unique = {};
var distinct = [];
arr.forEach(function (x) {
var key = fn(x);
if (!unique[key]) {
distinct.push(key);
unique[key] = true;
}
});
return distinct;
}
// usage
uniqueBy(array, function(x){return x.age;}); // outputs [17, 35]