Assuming I have the following:
var array =
[
{\"name\":\"Joe\", \"age\":17},
{\"name\":\"Bob\", \"age\":17},
{\"name\":\"Carl\
underscore.js
_.uniq(_.pluck(array,"age"))
Using Lodash
var array = [
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
];
_.chain(array).map('age').unique().value();
Returns [17,35]
function get_unique_values_from_array_object(array,property){
var unique = {};
var distinct = [];
for( var i in array ){
if( typeof(unique[array[i][property]]) == "undefined"){
distinct.push(array[i]);
}
unique[array[i][property]] = 0;
}
return distinct;
}
There are many valid answers already, but I wanted to add one that uses only the reduce()
method because it is clean and simple.
function uniqueBy(arr, prop){
return arr.reduce((a, d) => {
if (!a.includes(d[prop])) { a.push(d[prop]); }
return a;
}, []);
}
Use it like this:
var array = [
{"name": "Joe", "age": 17},
{"name": "Bob", "age": 17},
{"name": "Carl", "age": 35}
];
var ages = uniqueBy(array, "age");
console.log(ages); // [17, 35]
Just found this and I thought it's useful
_.map(_.indexBy(records, '_id'), function(obj){return obj})
Again using underscore, so if you have an object like this
var records = [{_id:1,name:'one', _id:2,name:'two', _id:1,name:'one'}]
it will give you the unique objects only.
What happens here is that indexBy
returns a map like this
{ 1:{_id:1,name:'one'}, 2:{_id:2,name:'two'} }
and just because it's a map, all keys are unique.
Then I'm just mapping this list back to array.
In case you need only the distinct values
_.map(_.indexBy(records, '_id'), function(obj,key){return key})
Keep in mind that the key
is returned as a string so, if you need integers instead, you should do
_.map(_.indexBy(records, '_id'), function(obj,key){return parseInt(key)})
I wrote my own in TypeScript, for a generic case, like that in Kotlin's Array.distinctBy {}
...
function distinctBy<T, U extends string | number>(array: T[], mapFn: (el: T) => U) {
const uniqueKeys = new Set(array.map(mapFn));
return array.filter((el) => uniqueKeys.has(mapFn(el)));
}
Where U
is hashable, of course. For Objects, you might need https://www.npmjs.com/package/es6-json-stable-stringify