How to use filter() and indexOf() methods In Javascript
The approach uses filter() and indexOf() to create a unique array by checking the index of each object’s first occurrence based on JSON string representation for precise comparison. This ensures the removal of duplicate objects from the original array.
Syntax:
let arr = inputArray.filter((value, index, self) => {
return self.indexOf(value) === index;
});
Example: Filtering out duplicate objects from the input array using filter() and indexOf() based on JSON string comparison, resulting in a unique array.
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Unique array using filter and indexOf functions
let uniqueArr = arr.filter(
(value, index, self) =>
self.findIndex((obj) =>
JSON.stringify(obj) === JSON.stringify(value)) ===
index
);
// Printing output
console.log("Input Array:", arr);
console.log("Unique Array:", uniqueArr);
Output
Input Array: [ { id: 1, name: 'Geek1' }, { id: 2, name: 'Geek2' }, { id: 1, name: 'Geek1' }, { id: 3, name: 'Geek3' } ] Unique Array: [ { id: 1, name: 'Geek1' }, { id: 2, name: 'Geek2' }, ...
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into a unique array of objects which are as follows:
Table of Content
- Using Set
- Using filter() and indexOf() methods
- Using Map
- Using reduce()
- Using Lodash Library
- Using some() Method