In this article, we'll look at how to get distinct values from an array of objects in JavaScript.
Using Array.prototype.map, Sets, and the Spread Operator
One way to get distinct values from an array of JavaScript objects is to use the array's map
method to get an array with the values of a property in each object.
Then we can remove the duplicate values with the Set
constructor.
And then we can convert the set back to an array with the spread operator.
For instance, we can write:
const array = [{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
]
const unique = [...new Set(array.map(item => item.age))];
console.log(unique)
We have the array
array that has objects with the name
and age
properties.
And we want to get all the distinct values of the age
property.
To do this, we call array.map
with a callback that returns the age
property value from each object and put them in the array.
Then we pass the returned array into the Set
constructor.
And then we convert the set back to an array with the spread operator.
Therefore, unique
is [17, 35]
.
Using Array.prototype.map, Sets, and the Array.from
We can replace the spread operator with the Array.from
method for converting the set to an array
For instance, we can write:
const array = [{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
]
const unique = Array.from(new Set(array.map(item => item.age)));
console.log(unique)
to call Array.from
with the set as the argument instead of the spread operator.
And we get the same result as before.
Using Array.prototype.map and Array.prototype.filter
Instead of using the Set
constructor and the spread operator, we can also use the filter
method to get the distinct values
For instance, we can write:
const array = [{
"name": "Joe",
"age": 17
},
{
"name": "Bob",
"age": 17
},
{
"name": "Carl",
"age": 35
}
]
const unique = array
.map(item => item.age)
.filter((value, index, self) => self.indexOf(value) === index)
console.log(unique)
We call the filter
method with a callback that has the value
, index
, and self
parameters.
value
has the value of the array returned from map
.
index
has the index of the element of the array returned from map
that's being iterated through.
And self
is the array that's returned by map
.
And we return all the items that are the first instance of a given value with the indexOf
method.
indexOf
method returns the index of the first element of a value.
So we can use that to check against the index
to only return the first item of each instance of each value.
And we get the same result as before.
Conclusion
We can use native JavaScript array methods and the spread operator to get distinct property values from an array.
More content at plainenglish.io