How unique an array of object with js by properties

In this article, you will learn how to make an array of objects unique with js by properties.

Let's start with a simple array of integers:

                                        
                                            const items = [1,2,3,1,1,4,5];
const uniqueItems = new Set(items);
console.log(Array.from(uniqueItems));
                                        
                                    


First, we create a new Set to filter all the items, and we transform the set into an array using the Array.from method.

Now we will see the same logic but with string:

                                        
                                            const fruits = ["apple", "orange", "apple", "banana", "orange"];
const uniqueFuits = new Set(fruits);
console.log(Array.from(uniqueFuits));
                                        
                                    

It is basically the same thing: We take an array of strings, put them into a new set, and then transform the set back into an array with unique values.

What about if we want to make this case sensitive?

                                        
                                            const fruits = ["Apple", "apple", "applE","orange", "Orange"];
const uniqueFruits = new Map(
fruits.map((fruit) => [fruit.toLowerCase(), fruit]
);
console.log(uniqueFruits.values());
// ["Apple", "orange"]
                                        
                                    

In this case we use the map class and pass the fruit in lower case to make it case sensitive and the use the fruit as value then we get the values as array.

When we need to filter the values by a property of an object we can use the Map class too example:

                                        
                                            const friends = [ 
{ id: 1, name: "Harry Portter", age: 18},
{ id: 2, name: "Mary jen", age: 19},
{ id: 1, name: "Harry Portter", age: 18}
];
const uniqueFriendsById = new Map(
friends.map(friend => [
friend.id,
friend
])
);
console.log(uniqueFriend.values());
/* [ 
{ id: 1, name: "Harry Portter", age: 18},
{ id: 2, name: "Mary jen", age: 19}
]
*/
                                        
                                    

In the last example you see how you can get the unique array of object by a property.

Now we will get the unique object by any properties:

                                        
                                            const friends = [ 
{ name: "Harry Portter", age: 18},
{ name: "Mary jen", age: 19},
{ name: "Harry Portter", age: 18}
];
const uniqueFriendsById = new Map(
friends.map(friend => [
Object.keys(friend).join('-'),
friend
])
);
console.log(uniqueFriend.values());
/* [ 
{ name: "Harry Portter", age: 18},
{ name: "Mary jen", age: 19}
]
*/
                                        
                                    

On this case we use all the properties of the object as unique id.