Languages
[Edit]
EN

JavaScript - remove all duplicates from array of objects

0 points
Created by:
Gaia-Kirby
810

In this article, we would like to show you how to remove all duplicates from an array of objects in JavaScript.

1. Practical example

In this section, we present a practical example of how to use filter() and findIndex() methods to remove duplicate elements from an array of objects.

// ONLINE-RUNNER:browser;

let array = [
    { type: 1, name: 'a' },
    { type: 2, name: 'b' },
    { type: 2, name: 'b' },
];

array = array.filter(
    (value, index, self) => index === self.findIndex((item) => item.type === value.type && item.name === value.name)
);

console.log(JSON.stringify(array));

2. Array inside object

In this example, we present how to use filter() and findIndex() methods to remove duplicate elements from an array of objects which is placed inside an object.

// ONLINE-RUNNER:browser;

const object = {
    array: [
        { type: 1, name: 'a' },
        { type: 2, name: 'b' },
        { type: 2, name: 'b' }
    ]
};

object.array = object.array.filter(
    (value, index, self) => index === self.findIndex((item) => item.type === value.type && item.name === value.name)
);

console.log(JSON.stringify(object.array));

 

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Array.prototype.findIndex() - JavaScript | MDN

Alternative titles

  1. JavaScript - remove all duplicate elements from array of objects
  2. JavaScript - remove all duplicate items from array of objects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join