Home >Web Front-end >JS Tutorial >How to Efficiently Remove Duplicate Objects from an Array in JavaScript?

How to Efficiently Remove Duplicate Objects from an Array in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 06:10:54684browse

How to Efficiently Remove Duplicate Objects from an Array in JavaScript?

How to Remove Duplicate Objects from an Array

When working with an array of objects, it's often necessary to remove duplicates. The ES6 filter method provides an elegant solution for this task.

ES6 Magic

obj.arr = obj.arr.filter((value, index, self) =>
index === self.findIndex((t) => (

t.place === value.place && t.name === value.name

))
)

This code compares each element in the array with all subsequent elements. If a duplicate is found, it is filtered out.

Generic Solution

For a more generic approach:

const uniqueArray = obj.arr.filter((value, index) => {
const _value = JSON.stringify(value);
return index === obj.arr.findIndex(obj => {

return JSON.stringify(obj) === _value;

});
});

This strategy serializes each object to a string and compares the strings to identify duplicates.

Property-Based Comparison

Using the property strategy:

const getUniqueItemsByProperties = (items, propNames) =>
items.filter((item, index, array) =>

index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))

);

This approach provides flexibility in specifying the properties on which uniqueness is determined.

Wrapped Property Strategy

To allow for both array and single property names:

const getUniqueItemsByProperties = (items, propNames) => {
const propNamesArray = Array.from(propNames);

return items.filter((item, index, array) =>

index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))

);
};

Explanation

The key idea here is to use the filter method to identify duplicates. The uniqueness criteria is determined by the comparison logic, which can be customized based on the object properties or a serialization strategy.

The above is the detailed content of How to Efficiently Remove Duplicate Objects from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn