fliter array of objects unique value of property code example
Example 1: filter array with unique objects javascript
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);
Example 2: javascript unique array of objects by property
const array =
[
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
]
function uniqueByKey(array, key) {
return [...new Map(array.map((x) => [x[key], x])).values()];
}
console.log(uniqueByKey(array, 'age'));