How to check duplicates in array except 0 javascript

别来无恙 提交于 2020-01-04 02:05:30

问题


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)
 

回答1:


Object cannot be compared the way other primitive type compared.

i wrote a function to solve what you asked, its completely different from what you implemented and it may be not good in terms of performance and practicality

var data = [{id: 0},  {id: 1}, {id: 2}, {id: 0},{id: 3}];

function isDuplicatedata() {            
  for(var i = 0; i < data.length; i++) {
    if(data[i].id === 0)
      continue;
    for(var j = i+1; j < data.length; j++) {
      if(data[j].id === data[i].id)
        return true;
    }
  }
  return false;
}

alert(isDuplicatedata())



回答2:


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



回答3:


I recommend sorting the array and checking if the current id is the same as the previous id. This method traverses the array only 2 times.

var data = [{id: 0},  {id: 1}, {id: 3}, {id: 0}];
//Sort the array so it becomes [0,0,1,3]
data.sort(function(a, b) {
  if (a.id < b.id)
    return -1;
  else if (a.id > b.id)
    return 1;
  else
    return 0;
});
//Now check all the objects and compare them with the previous array element
var isDuplicatedata = false;
for (var i = 1, l = data.length; i < l; i++) {
  var rec = data[i],
    previousRec = data[i - 1];
  //Skip zeroes
  if (rec.id !== 0 && rec.id === previousRec.id) {
    isDuplicatedata = true;
    break;
  }
}

alert(isDuplicatedata);



回答4:


When you are you using lodash you could do it like this:

var data = [{id: 0},  {id: 1}, {id: 3}, {id: 0}];

// group by id
var result = _.groupBy(data, function (item) {
     return item.id;
});

// remove the 0
delete result[0]

// check if there are duplicates
var isDuplicatedData = _.some(Object.keys(result), function (k) {
     return result[k].length > 1;
});

If you don't have lodash, here are the used functions in plain javascript:

var groupBy = function(arr, grouper) {
    var map = {};
    (arr || []).forEach(function(element) {
        var key = grouper(element);
        map[key] = map[key] || [];
        map[key].push(element);
    });
    return map;
 };
var some = function (arr, predicate) {
    return (arr || []).reduce(function (a, b) {
        return a || predicate(b);
    }, false);
};

here is a jsfiddle with the lodash-one: https://jsfiddle.net/awuq1ayx/




回答5:


var data = [{id: 0}, {id: 1}, {id: 3}, {id: 0},];         
var checkdata= data.map(function(item){ return item.id })
    .filter(function(item){ return item !== 0 });
var isDuplicatedata = checkdata.sort() + "" != checkdata.sort().reduce(function(p, c){
    if (c != p[0]) p.unshift(c);
    return p;
}, []).sort();

alert(isDuplicatedata)



回答6:


If your data is only objects, you can write a function that checks if 2 objects equals.

Object.prototype.equals = function(x)
{
    for(p in this)
    {
        switch(typeof(this[p]))
        {
            case 'object':
                if (!this[p].equals(x[p])) { return false }; break;
            case 'function':
                if (typeof(x[p])=='undefined' || (p != 'equals' && this[p].toString() != x[p].toString())) { return false; }; break;
            default:
                if (this[p] != x[p]) { return false; }
        }
    }

    for(p in x)
    {
        if(typeof(this[p])=='undefined') {return false;}
    }

    return true;
}

then use for loop.

    function isDuplicatedata( data ) {
    for( var i = 0; i < data.length - 1; i ++ ) {
        for( var j = i + 1; j < data.length; j ++ ) {
            if( data[i].equals(data[j])) {
                return true;
            }
        }
    }

    return false;
}

With this method you can check any kind of data. Please note, that complexity of this method is O(n^2).



来源:https://stackoverflow.com/questions/34740869/how-to-check-duplicates-in-array-except-0-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!