1

Trying to get _.uniq() working on the following structure:

[
    {'x' : 1, 'y': 2},
    {'x' : 1, 'y': 2},
    {'x' : 2, 'y': 3},
    {'x' : 2, 'y': 4},
    {'x' : 3, 'y': 4}
]

where the result should be:

[
    {'x' : 1, 'y': 2},
    {'x' : 2, 'y': 3},
    {'x' : 2, 'y': 4},
    {'x' : 3, 'y': 4}
]

ie duplicate items removed. I'd like to avoid stringify, because I then just have to parse each back out to a JSON object.

Any help would be appreciated.

EDIT: tring Matt's solution below, I'm missing something I think - this doesn't work. If I log the values for a and b, I see

_.uniq($scope.validNotes, function (a, b) {
    console.log(a, b);
    return a.x === b.x && a.y === b.y;
});


Object {x: 2, y: 3} 0 
Object {x: 1, y: 0} 1 
Object {x: 2, y: 3} 2 
Object {x: 3, y: 2} 3 
Object {x: 4, y: 2} 4
Object {x: 5, y: 1} 5

Which obviously means I'll never find any dupes

Nathan
  • 949
  • 1
  • 20
  • 35
  • possible duplicate of [Javascript - Quickly remove duplicates in object array](http://stackoverflow.com/questions/14650626/javascript-quickly-remove-duplicates-in-object-array) – Vicky Gonsalves Nov 11 '13 at 12:08
  • possible duplicate of [Removing duplicate objects with Underscore for Javascript](http://stackoverflow.com/questions/9923890/removing-duplicate-objects-with-underscore-for-javascript) – Matt Nov 11 '13 at 12:10

2 Answers2

9

Because two objects are not == or ===, just because they have the same keys, you will need to use the [iterator] argument of the uniq() function;

_.uniq(myArray, function (item) {
    return item.x + item.y;
});

Note you'll need to return a unique string combination; consider the case of { x: 11, y: 1 } and { x: 1, y: 11 }; my code will resolve both to 111, and treat them as the same.

Something like:

_.uniq(myArray, function (item) {
    return 'x:' + item.x + 'y:' + item.y;
});

... would be more resilient, but it depends on the values of your data, of course.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • @Nathan: Eugh, sorry... noobed the arguments of the iterator. Try now? – Matt Nov 11 '13 at 12:27
  • 1
    awesome, thanks. Wasn't sure how the iterator worked, makes sense now. Works even better once I realised my data was incorrect too – Nathan Nov 11 '13 at 20:43
0

If you have abstract data structure in your JSON, it will be better to compare array elements one bt one like strings, using stringify. Because you have new object in every array element, every literal object notation ie {} creates new object in javascript language and it's doesn't metter has it the same properties or not.

But, if you have stucture like x,y use Matt answer

Community
  • 1
  • 1
Alex
  • 11,115
  • 12
  • 51
  • 64