Reputation: 30178
I have two arrays of data:
markerArray = [{
properties: {id: 1}
},
{
properties: {id: 2}
}];
and
data = [
{ id: 1},
{ id: 2},
{ id: 3}
]
I want to, as quickly as possible, create a new array of objects from data
that have an id that does not exist in markerArray's properties.id
Lodash / underscore are an option.
Upvotes: 0
Views: 52
Reputation: 11211
Here's a lodash solution:
_.reject(data, _.flow(
_.identity,
_.property('id'),
_.partial(_.includes, _.map(markerArray, 'properties.id'))
));
Basically, you want to use reject() to remove the unwanted items from data (by creating a copy, not by modifying the original). We use flow() to build the callback function that decide which items are rejected. Here's the breakdown:
reject()
are given several arguments - we only care about the first one. This is what identity() does, it passes the first argument to the next function in flow()
.id
property of the given item. Again, this id
is input for the next flow()
function.markerArray
. The function we're creating a partial from is includes(). If the id from data
is in this array, we can remove it from the results.Upvotes: 0
Reputation: 1553
Not sure about the fastest, but certainly the simplest is with lodash:
_.difference(_.pluck(data, "id"),
_.pluck(_.pluck(markerArray, "properties"),"id"));
Upvotes: 1
Reputation: 171690
Suggest you map an array that just contains the ID's first:
var idArray= markerArray.map(function(item){
return item.properties.id
});
//[1,2]
Then to find matches that don't exist in id array:
var result = data.filter(function(item){
return idArray.indexOf(item.id) === -1;
});
Upvotes: 0
Reputation: 11725
You could use map
to map the IDs and then use filter
to look into your data
array:
var ids = markerArray.map(function(item) {
return item.properties.id;
});
var result = data.filter(function(item) {
return ids.indexOf(item.id) < 0;
});
Upvotes: 0