Converting Array to Set and Remove Duplicates
- A Set object holds only unique values of any type. This property can be used to store only the objects that are unique in the array.
- Each object of the array is first converted into a JSON-encoded string using the JSON.stringify method.
- The JSON-encoded string is then mapped to an array using the map() method. A new set is created by passing this array to the new set constructor.
- This step will remove all the duplicate elements as the JSON-encoded strings will be the same for the same elements.
- The set is then converted to an Array using the from() method, passing the set as a parameter. This array will not have duplicated objects.
Example: In this example, we will remove the duplicate values from an array of objects by converting the array to a set to remove the duplicates.
function removeDuplicates() {
// Create an array of objects
books = [
{ title: "C++", author: "Bjarne" },
{ title: "Java", author: "James" },
{ title: "Python", author: "Guido" },
{ title: "Java", author: "James" },
];
jsonObject = books.map(JSON.stringify);
uniqueSet = new Set(jsonObject);
uniqueArray = Array.from(uniqueSet).map(JSON.parse);
console.log(uniqueArray);
}
removeDuplicates();
Output
[ { title: 'C++', author: 'Bjarne' }, { title: 'Java', author: 'James' }, { title: 'Python', author: 'Guido' } ]
How to Remove Duplicates from an Array of Objects in JavaScript?
This article focuses on removing duplicate object elements from the JavaScript array. We are provided with an array of objects, and our goal is to eliminate duplicate objects from the list.
These are the methods to solve this problem which are discussed below:
Table of Content
- Using One of the keys as Index
- Converting Array to Set and Remove Duplicates
- Using filter() and includes() Methods
- Using filter() and findIndex() Methods
- Using Lodash _.uniq() Method