In this article, we will learn how to get a unique object from an array.
Suppose you have an object named players like shown below in an image:
const Players = [ { id: 1, name: 'Kohli'}, { id: 2, name: 'Rohit'}, { id: 3, name: 'Dhoni'}, { id: 1, name: 'Kohli'}, { id: 2, name: 'Rohit'}, { id: 1, name: 'Kohli'}, { id: 2, name: 'Rohit'} ];
And you want to get unique values of the id attribute of each item from the array.
Here’s how you can get the unique list by key:
const key = 'id'; // set key to get unique list const unique = [...new Map(Players.map(item => [item[key], item])).values()]; console.log(unique);
Here you get a unique object list by filtering the key.
Hope this article helps you. Thanks for reading.