How to find duplicate values in a JavaScript array of objects, and output only unique values?

how to find duplicate values in array using javascript
how to find duplicate values in array of objects using javascript
javascript unique array of objects
remove duplicates from array javascript using for loop
javascript get unique values from two array of objects
javascript array push no duplicates
get unique values from array javascript
javascript make array unique

I'm learning JS. Supposing I have the below array of objects:

var family = [
  {
    name: "Mike",
    age: 10
  },
  {
    name: "Matt"
    age: 13
  },
  {
    name: "Nancy",
    age: 15
  },
  {
    name: "Adam",
    age: 22
  },
  {
    name: "Jenny",
    age: 85
  },
  {
    name: "Nancy",
    age: 2
  },
  {
    name: "Carl",
    age: 40
  }
];

Notice that Nancy is showing up twice (changing only the age). Supposing I want to output only unique names. How do I output the above array of objects, without duplicates? ES6 answers more than welcome.

Related (couldn't find a good way for usage on objects):

  • Remove Duplicates from JavaScript Array
  • Easiest way to find duplicate values in a JavaScript array

EDIT Here's what I tried. It works well with strings but I can't figure how to make it work with objects:

family.reduce((a, b) => {
  if (a.indexOf(b) < 0 ) {
    a.push(b);
  }
  return a;
},[]);

You could use a Set in combination with Array#map and a spread operator ... in a single line.

Map returns an array with all names, which are going into the set initializer and then all values of the set are returned in an array.

var family = [{ name: "Mike", age: 10 }, { name: "Matt", age: 13 }, { name: "Nancy", age: 15 }, { name: "Adam", age: 22 }, { name: "Jenny", age: 85 }, { name: "Nancy", age: 2 }, { name: "Carl", age: 40 }],
    unique = [...new Set(family.map(a => a.name))];

console.log(unique);

JavaScript Array Distinct(), Or wanted to get distinct objects from an array by a property? This blog post is for you. Primitive values in JavaScript are immutable values in… are often used as select options and we don't want duplicate option values. array, then filter the original array so that only first-occurred elements are kept. Supposing I want to output only unique names. How do I output the above array of objects, without duplicates? ES6 answers more than welcome. Related (couldn't find a good way for usage on objects): Remove Duplicates from JavaScript Array; Easiest way to find duplicate values in a JavaScript array; EDIT Here's what I tried. It works well with

The Solution

Store occurrences of name external to the loop in an object, and filter if there's been a previous occurrence.

https://jsfiddle.net/nputptbb/2/

var occurrences = {}

var filteredFamily = family.filter(function(x) {
  if (occurrences[x.name]) {
    return false;
  }
  occurrences[x.name] = true;
  return true;
})

you can also generalize this solution to a function

function filterByProperty(array, propertyName) {
  var occurrences = {}

  return array.filter(function(x) {
    var property = x[propertyName]
    if (occurrences[property]) {
      return false;
    }
    occurrences[property]] = true;
    return true;
  })
}

and use it like

var filteredFamily = filterByProperty(family, 'name')
Explanation

Don't compare objects using indexOf, which only uses the === operator between objects. The reason why your current answer doesn't work is because === in JS does not compare the objects deeply, but instead compares the references. What I mean by that you can see in the following code:

var a = { x: 1 }
var b = { x: 1 }

console.log(a === b) // false
console.log(a === a) // true

Equality will tell you if you found the same exact object, but not if you found an object with the same contents.

In this case, you can compare your object on name since it should be a unique key. So obj.name === obj.name instead of obj === obj. Moreover another problem with your code that affects its runtime and not its function is that you use an indexOf inside of your reduce. indexOf is O(n), which makes the complexity of your algorithm O(n^2). Thus, it's better to use an object, which has O(1) lookup.

How to get all unique values (remove duplicates) in a JavaScript , How to force Input field to enter numbers only using JavaScript ? If the current value does not exist in the output array with unique values, then add the element to the output How to remove object from array of objects using JavaScript ? Method 1: This method checked each value of the original array (listArray) with each value of output array (outputArray) where the duplicate values are removed. If the current value does not exist in the output array with unique values, then add the element to the output array. Example 1: This example generates an unique array of string values.

This will work fine.

const result = [1, 2, 2, 3, 3, 3, 3].reduce((x, y) => x.includes(y) ? x : [...x, y], []);

console.log(result);

JavaScript array: Find duplicate values in a array, Write a JavaScript program to find duplicate values in a JavaScript array. Sample Solution: JavaScript Code: function find_duplicate_in_array(arra1) { var object = {}; var result = []; arra1. Sample Output: ["4","7"]. Flowchart:. For finding duplicate values in JavaScript array, you’ll make use of the traditional for loops and Array reduce method. Using For Loop Let’s see how you can find duplicates in an array using for loop. The logic is you’ll separate the array into two array, duplicate array and unique array.

I just thought of 2 simple ways for Lodash users

Given this array:

let family = [
  {
    name: "Mike",
    age: 10
  },
  {
    name: "Matt",
    age: 13
  },
  {
    name: "Nancy",
    age: 15
  },
  {
    name: "Adam",
    age: 22
  },
  {
    name: "Jenny",
    age: 85
  },
  {
    name: "Nancy",
    age: 2
  },
  {
    name: "Carl",
    age: 40
  }
]

1. Find duplicates:

let duplicatesArr = _.difference(family, _.uniqBy(family, 'name'), 'name')

// duplicatesArr:
// [{ 
//   name: "Nancy", 
//   age: 2 
// }]

2 Find if there are duplicates, for validation purpose:

let uniqArr = _.uniqBy(family, 'name')

if (uniqArr.length === family.length) {
    // No duplicates
}

if (uniqArr.length !== family.length) {
    // Has duplicates
}

How to Remove Array Duplicates in ES6 - DailyJS, Set is a new data object introduced in ES6. When you pass in an array, it will remove any duplicate values. Because Set only allows unique values, all duplicates will be removed. is always a bit more tricky to understand, so let's also step into each case and see the output: I never understood JavaScript closures. That way, we filter out the values, and remaining values form an array, and that result array has unique values. The native method filter will loop through the array and leave only those entries that pass the given callback function unique. The unique function checks, if the given value is the first occurring.

With the code you mentioned, you can try:

family.filter((item, index, array) => {
  return array.map((mapItem) => mapItem['name']).indexOf(item['name']) === index
})

Or you can have a generic function to make it work for other array of objects as well:

function printUniqueResults (arrayOfObj, key) {
  return arrayOfObj.filter((item, index, array) => {
    return array.map((mapItem) => mapItem[key]).indexOf(item[key]) === index
  })
}

and then just use printUniqueResults(family, 'name')

(FIDDLE)

Filter Unique in Javascript, use .filter on array's in Javascript to get all the unique values in the array. The purpose of applying .filter to an array is to remove unwanted values i.e. duplicates. It only looks at the array elements that precede the current element, own cache object, it's not hard to store values in a cache and provide  To find duplicate values in JavaScript, you can try to run the following code:ExampleLive Demo

How To Get Javascript Unique Array Using Filter() Method, Distinct values in array in Javascript. Primitive values in JavaScript are immutable values except for objects. To find a unique array and remove all the duplicates from the array, you can The native method filter will loop through the Array and leave only those entries that It will give the same output. Finding duplicate property values in an Array of Objects in JavaScript is not always that simple if you thought, so let’s dive in! A few days ago I needed to work this out, so I thought let’s write it down, so I could use it later again! Array of Objects. Let’s define an example Array of Objects, where each Object is a user:

JavaScript: Remove Duplicates from an Array, A Set is a collection of unique values. The following example uses a Set to remove duplicates from an array: Output: 1. The duplicate item is the item whose its index is different from its the filter() method to include only elements whose indexes match their indexOf values: Next Sort an Array of Objects in JavaScript  See the Pen JavaScript - Find duplicate values in a array - array-ex- 20 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus. Previous: write a JavaScript program to compute the sum of each individual index value from the given arrays.

How to Remove Array Duplicates in ES6, Set is a new data object introduced in ES6. When you pass in an array, it will remove any duplicate values. Because Set only allows unique values, all duplicates will be removed. a bit more tricky to understand, so let's also step into each case and see the output: How to Check if NaN is equal to NaN in JavaScript  Given an array of n + 1 integers between 1 and n, find one of the duplicates.If there are multiple possible answers, return one of the duplicates.If there is no duplicate, return -1.Example:Input: [1, 2, 2, 3] Output: 2Input: [3, 4, 1, 4, 1] Output: 4 or 1.

Comments
  • can you post what you have tried?
  • Actually I tried most of answers from both related questions I mentioned.
  • can someone explain why those downvotes? Should I copy/paste any code that doesn't work here just to say I tried?
  • its because this isnt actually too hard, but require a little bit more research, google this: get unique objects array javascript
  • @RicoLetterman I edited my answer to address your edit, and why it doesn't work.
  • Is there a way to output my array of objects instead of this flat array?
  • what about your question I want to output only unique names.? if not, which one would you like to get the first object, or the last?
  • Very well done. I like the two options you thoroughly explained.
  • hi @Nina Scholz it's working fine but not work i IE11 give anyother solution
  • @jose, this question is marked ES6, and IE11 does not support it. you could use a hash table instead with an object and collect all names there.
  • its probably because your fiddle write to the console...was running the fiddle, looking at o/p, and wondering anything worked...not really bothering to check the code first (and see its writing to console)
  • I really appreciate this answer -- it's cross-browser, performant, and easy-to-read.