Pregunta

I'm trying to remove objects from an array of object using a delta data i'm getting from server. I'm using underscore in my project.

Is there a straight forward way to do this, rather going with looping and assigning ?

Main Array

var input = [
   {name: "AAA", id: 845,status:1},
   {name: "BBB", id: 839,status:1},
   {name: "CCC", id: 854,status:1}
];

Tobe Removed

var deltadata = [
   {name: "AAA", id: 845,status:0},
   {name: "BBB", id: 839,status:0}
];

Expected output

var finaldata =  [
  {name: "CCC", id: 854,status:1}
]
¿Fue útil?

Solución 2

Here's a simple solution. As others have mentioned, I don't think this is possible without a loop. You could also add checks for status and name in the condition, as this just compares IDs.

var finaldata = input.filter(function(o) {
    for (var i = 0; i < deltadata.length; i++)
       if (deltadata[i].id === o.id) return false;
    return true;
});

Otros consejos

Try this

var finaldata = _.filter(input, function(item) {
    return !(_.findWhere(deltadata, {id: item.id}));
});

It does assume that you have unique ID's. Maybe you can come up with something better.

A simple filter will do it:

var finaldata = _.filter(input, function(o) {
    return _.findWhere(deltadata, o) === undefined;
});

A little more efficient than the findWhere would be creating a lookup map with ids to remove, and then filtering by that:

var idsToRemove = _.reduce(deltadata, function(m, o) {
    m[o.id] = true;
    return m;
}, {});
var finaldata = _.reject(input, function(o) { return o.id in idsToRemove; });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top