How to use some() Method In Javascript
This approach uses the some() method to create a unique array of objects. The some() method checks if at least one element in the array passes the test implemented by the provided function. If an object with the same key already exists in the unique array, it is not added again.
Syntax:
array.some(callback(element[, index[, array]])[, thisArg])
Example: The below example uses the some() method to remove duplicate objects from an array based on a specific key in JavaScript.
let arr = [
{ id: 1, name: "Geek1" },
{ id: 2, name: "Geek2" },
{ id: 1, name: "Geek1" },
{ id: 3, name: "Geek3" },
];
// Using some() to ensure unique objects
let uniqueArr = [];
arr.forEach(obj => {
if (!uniqueArr.some(item => item.id === obj.id && item.name === obj.name)) {
uniqueArr.push(obj);
}
});
// 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