Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check duplicates in array except 0 javascript

I have a variable data a array of objects. Now I want to check if there a duplicates values except 0. What I've done so far is the code snippet below:

The alert shows me true it should be false cause 0 is not included for checking. Please help. Thanks

var data = [{id: 0},  {id: 1}, {id: 3}, {id: 0},];
            
            
var checkdata= data.map(function(item){ 
return item.id });
var isDuplicatedata= checkdata.some(function(item, idx){ 
    return checkdata.indexOf(item) != idx 
});
            
alert(isDuplicatedata)
 
like image 847
qazzu Avatar asked Dec 14 '25 05:12

qazzu


1 Answers

You can use Array.prototype.some()

The some() method tests whether some element in the array passes the test implemented by the provided function.

and a temporary object.

var data = [{ id: 0 }, { id: 1 }, { id: 3 }, { id: 0 } ],
    object = {},
    duplicate = data.some(function (a) {
        if (a.id === 0) {
            return false;
        }
        if (a.id in object) {
            return true;
        }
        object[a.id] = true;
    });

document.write(duplicate);
like image 68
Nina Scholz Avatar answered Dec 15 '25 20:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!