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

How to Remove Duplicate Objects from an Array in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 20:17:10292browse

How to Remove Duplicate Objects from an Array in JavaScript?

How to Eliminate Duplicate Objects from an Array

Your query revolves around efficiently removing duplicate objects from an array within an object. Let's explore some effective techniques to achieve this goal.

ES6 Solution:

Introducing a touch of ES6 elegance, we can utilize the filter and findIndex methods:

obj.arr = obj.arr.filter((value, index, self) =>
  index === self.findIndex((t) => (
    t.place === value.place && t.name === value.name
  ))
);

This approach ensures that only the unique objects remain in the array.

Generic Solution:

For a more versatile solution, consider:

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

This method employs JSON stringification to compare objects based on their property values.

Property-Based Filtering:

Alternatively, you can define a function to compare objects by specific properties:

const isPropValuesEqual = (subject, target, propNames) =>
  propNames.every(propName => subject[propName] === target[propName]);

const getUniqueItemsByProperties = (items, propNames) => 
  items.filter((item, index, array) =>
    index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
  );

This function returns an array containing unique objects based on the specified property names.

Explanation:

  • filter: Removes duplicate objects that satisfy the given criterion.
  • findIndex: Returns the index of the first occurrence of an object that matches a specified criterion.

By leveraging these techniques, you can effectively remove duplicate objects from an array, allowing you to work with a clean and concise dataset.

The above is the detailed content of How to 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