mheavers
mheavers

Reputation: 30178

quickest way to identify objects in array which have properties that are unique from properties in another object array

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

Answers (4)

Adam Boduch
Adam Boduch

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:

  • Callback functions passed to 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().
  • The property() function returns a new function. This new function will return the id property of the given item. Again, this id is input for the next flow() function.
  • We then use partial() to do the actual filtering. The partially-applied argument is an array of IDs from the 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

show-me-the-code
show-me-the-code

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

charlietfl
charlietfl

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

Buzinas
Buzinas

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

Related Questions