Saimir Kapaj
Saimir Kapaj

Saimir Kapaj

Remove duplicates from an Array of Objects

Saimir Kapaj's photo
Saimir Kapaj
·Oct 13, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

In this post, we'll see how to remove duplicates from an array of objects.

Let's suppose we have an array of products. Each product is an object with three properties: id, name, and price.

const products = [
  {
    id: 1,
    name: 'Product 1',
    price: 120,
  },
  {
    id: 2,
    name: 'Product 2',
    price: 90,
  },
  {
    id: 3,
    name: 'Product 3',
    price: 150,
  },
  {
    id: 1,
    name: 'Product 1',
    price: 120,
  }
];

As you can see the first product and the last one have the same id. In our case, we don't want to have multiple products with the same id.

To remove duplicates we'll use find() and reduce() methods.

const newProducts = products.reduce((accumulator, currentValue) => {
  const exist = accumulator.find(item => item.id === currentValue.id);

  if(exist) {
    return accumulator;
  }
  return accumulator.concat(currentValue);
}, []);

console.log(newProducts);
/*
[
  {
    id: 1,
    name: 'Product 1',
    price: 120,
  },
  {
    id: 2,
    name: 'Product 2',
    price: 90,
  },
  {
    id: 3,
    name: 'Product 3',
    price: 150,
  }
];
*/

In the example above the reduce() method takes a callback function that is executed in each element of the array and an initial value ( an empty array [] ).

The callback function has two arguments. The accumulator and the currentValue.

The accumulator is the value of the previous execution, where we add values of each array element. The currentValue is the value of the array element in the current iteration.

By using the find() method, in each execution we check if in the accumulator exists any other element ( product ) with the same id of the currentValue. If it exists, we return the accumulator, otherwise we return the accumulator and the currentValue. In our case, we add the currentValue to the accumulator by using the concat() method.

If you prefer, instead of the concat() method, you can use the spread operator.

// return accumulator.concat(currentValue);
return [...accumulator, currentValue];
 
Share this