0

I have two arrays:

var one = [
    Object { _id="53c907016b7536a18b0001ab", title="..." },
    Object { _id="53c90942b879875e2b0001ec", title="..." }
]

var two = [
    Object { _id="53c907016b7536a18b0001ab", title="..." }
]

I am looking to find the difference, i.e.

[
    Object { _id="53c90942b879875e2b0001ec", title="..." }
]

Using underscore.js, I tried:

var difference = _.difference( one, two );

but that returns the whole one array, rather than the difference.

I assume the problem is that my arrays contain objects, rather than primitives. If that is the case, how can I tell underscore to use the values of _id for the comparison?

Ben
  • 15,938
  • 19
  • 92
  • 138
  • Thanks, I think this answer, http://stackoverflow.com/a/19547466/795016, solves my problem. – Ben Jul 18 '14 at 13:33

1 Answers1

1

Try following, it works for just two arrays

_.reject(one, function(obj){ return _.findWhere(two, obj); });

But objects should be like bellow

var one = [
{ _id:"53c907016b7536a18b0001ab", title:"..." },
{ _id:"53c90942b879875e2b0001ec", title:"..." }
]

var two = [
    { _id:"53c907016b7536a18b0001ab", title:"..." }
]
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • Thanks! Does anyone know how this performs compared to `_.filter(one, function(obj){ return !_.findWhere(two, obj); });` – Ben Jul 18 '14 at 13:34
  • I don't know but I use is like this because just I tried to escape `return !something`. – Mritunjay Jul 18 '14 at 13:36