Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if the array of objects have duplicate property values?

I need some help with iterating through array, I keep getting stuck or reinventing the wheel.

values = [     { name: 'someName1' },     { name: 'someName2' },     { name: 'someName1' },     { name: 'someName1' } ] 

How could I check if there are two (or more) same name value in array? I do not need a counter, just setting some variable if array values are not unique. Have in mind that array length is dynamic, also array values.

like image 793
be-codified Avatar asked Jun 09 '15 14:06

be-codified


People also ask

How do you check if a property is an array of objects?

Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .

How do you get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.


1 Answers

Use array.prototype.map and array.prototype.some:

var values = [     { name: 'someName1' },     { name: 'someName2' },     { name: 'someName4' },     { name: 'someName2' } ];  var valueArr = values.map(function(item){ return item.name }); var isDuplicate = valueArr.some(function(item, idx){      return valueArr.indexOf(item) != idx  }); console.log(isDuplicate);
like image 140
Amir Popovich Avatar answered Sep 27 '22 19:09

Amir Popovich