---
title: Removing Objects from Array with Duplicate Values Using .reduce()
description: We'll take a look at an easy way to remove objects from an Array in JavaScript using the .reduce() method
date: 2020-01-29
tags: JavaScript, reduce, objects, arrays
source: https://brianchildress.co/blog/remove-objects-from-array-with-duplicate-values
---

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

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:

```js
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:

```js
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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) method.

```js
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.
