3

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
  • Perpahs u actually meant 0 as for null? Because it makes a huge difference. Commented Jan 12, 2016 at 10:18

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

The answer should be false cause the 0 is not included for checking
Very clean, concise and efficient. Nice
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())

Comments

1

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

Comments

1

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/

Comments

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

5 Comments

The code works but why are you comparing a stringified array with an array?
The array on the right hand side gets cast to a string implicitly, see ecma-international.org/ecma-262/5.1/index.html#sec-11.9.3
Ah so your code is relying on the type coercion done by the equality operator.
yeah exactly, for enhanced brevity to take lead in the shortest answer high score ranking of this thread
Please strive for better quality and understanding of the problem instead of worrying about less bytes :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.