Removing Objects from Array with Duplicate Values Using .reduce()

Jan 29, 2020 min read

Finding and remove duplicate information in an array is a very common task. In JavaScript this is pretty easy using the .reduce() method.

Let’s say we have a simple array of objects like this:

const myArray = [{
  first_name: 'brian',
  last_name: 'wayne',
  age: 36
},{
  first_name: 'jane',
  last_name: 'tandy',
  age: 34
},{
  first_name: 'william',
  last_name: 'wayne',
  age: 55
}]

And I want to find and remove all objects with a duplicate last_name. Using the built-in .reduce() method we can do it using something like this:

const removeDuplicates = (array, key) => {
  return array.reduce((acc, element) => {
    if (!acc.find(temp => temp[key] === element[key])) {
      acc.push(element);
    }
    return acc;
  }, []);
}

console.log(removeDuplicates(myArray, 'last_name'));

// [ { first_name: 'brian', last_name: 'wayne', age: 36 }, 
//   { first_name: 'jane', last_name: 'tandy', age: 34 } ] 

What’s going on here?

We’ve created a simple function, removeDuplicates, that takes two arguments, array and key. array is the array that we want to “reduce” by removing duplicates, key is the name of the key that we want to search for in the existing objects currently being tracked. Inside the removeDuplicates method we return array.reduce().

.reduce() is an array method built into JavaScripts Array prototype for evaluating and returning a single output value. For us the output value is a new array, represented by the acc variable. acc is short for Accumulator and is used by the .reduce() method to track or accumulate all values that meet our criteria.

Our criteria for determining if an object stays in the returned array is whether or not another object in the acc array already has a matching key with the same value. For this we use the .find() method.

if (!acc.find(temp => temp[key] === element[key])) {

If no object is “found” with a matching key and value the object is then pushed onto the acc array. Finally, after reviewing all of the objects in the array we return the acc array.