javascriptarraysunique

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.


Solution

  • 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);