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.
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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With