Crystal
Crystal

Reputation: 29518

Find objects in an array that are the same, not remove them

I'm trying to find objects in an array that are the same to flag them in the UI. I can't seem to use undescore to do it.

I was doing this:

var a = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'},  {'id': 9, 'name': 'nick'}, {'id': 1, 'name': 'jake' } ];
var eaches = _.each(a, function (obj) {
  _.find(a, function () {
    return _.isEqual(a, obj);
  });
});

Thanks in advance!

Upvotes: 1

Views: 72

Answers (1)

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

Seems you need something like this:

var a = [{
    'id': 1,
    'name': 'jake'
}, {
    'id': 4,
    'name': 'jenny'
}, {
    'id': 9,
    'name': 'nick'
}, {
    'id': 1,
    'name': 'jake'
}];

var eq = [];

_.each(a, function (x, i) {
    var e = _.find(a, function (y, j) {
        return i !== j && _.isEqual(x, y);
    });
    if (e) {
        eq.push(x);
    }
});

console.log(eq);

http://jsfiddle.net/f0t0n/WBbs5/


UPDATE:
Custom "_.uniq" based on _.isEqual instead of === strict comparison:

var uniqEq = _.reject(eq, function(x, i) {
    return _.find(eq, function(y, j) {
        return i < j && _.isEqual(x, y);
    });
});

http://jsfiddle.net/f0t0n/hzBBA/

Upvotes: 1

Related Questions