Assuming I have the following:
var array =
[
{\"name\":\"Joe\", \"age\":17},
{\"name\":\"Bob\", \"age\":17},
{\"name\":\"Carl\
For those who want to return object with all properties unique by key
const array =
[
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
]
const key = 'age';
const arrayUniqueByKey = [...new Map(array.map(item =>
[item[key], item])).values()];
console.log(arrayUniqueByKey);
/*OUTPUT
[
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
]
*/
// Note: this will pick the last duplicated item in the list.
Simple distinct filter using Maps :
let array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
];
let data = new Map();
for (let obj of array) {
data.set(obj.age, obj);
}
let out = [...data.values()];
console.log(out);
[...new Set([
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
].map(({ age }) => age))]
You may be interested in unique set of objects based on one of the keys:
let array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
]
let unq_objs = [...new Map(array.map(o =>[o["age"], o])).values()];
console.log(unq_objs)
//result
[{name: "Bob", age: 17},
{name: "Carl", age: 35}]
Simple one-liner with great performance. 6% faster than the ES6 solutions in my tests.
var ages = array.map(function(o){return o.age}).filter(function(v,i,a) {
return a.indexOf(v)===i
});
If you are using ES6/ES2015 or later you can do it this way:
const data = [
{ group: 'A', name: 'SD' },
{ group: 'B', name: 'FI' },
{ group: 'A', name: 'MM' },
{ group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
Here is an example on how to do it.