how to get unique values in array of objects in javascript 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 map return array with distinc values
let array = [
{ "name": "Joe", "age": 17 },
{ "name": "Bob", "age": 17 },
{ "name": "Carl", "age": 35 }
];
array.map(item => item.age)
.filter((value, index, self) => self.indexOf(value) === index)
> [17, 35]
Example 3: javascript get unique values from array
const myArray = [1,2,3,1,5,8,1,2,9,4];
const unique = [...new Set(myArray)];
const myString = ["a","b","c","a","d","b"];
const uniqueString = [...new Set(myString)];