识别数组中对象的最快方法,这些对象具有与另一个对象数组中的属性不同的属性

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

我有两个数据数组:

markerArray = [{
  properties: {id: 1}
},
{
  properties: {id: 2}
}];

data = [
 { id: 1},
 { id: 2},
 { id: 3}
]

我想尽快从 data 创建一个新的对象数组,这些对象的 ID 在 markerArray 的 properties.id

中不存在

Lodash / 下划线是一个选项。

您可以使用 map 映射 ID,然后使用 filter 查看您的 data 数组:

var ids = markerArray.map(function(item) {
  return item.properties.id;
});

var result = data.filter(function(item) {
  return ids.indexOf(item.id) < 0;
});

建议您映射一个仅包含 ID 第一个的数组:

var idArray= markerArray.map(function(item){
  return item.properties.id
});
//[1,2]

然后查找 ID 数组中不存在的匹配项:

var result = data.filter(function(item){ 
      return idArray.indexOf(item.id) === -1;
});

不确定最快的,但肯定是使用 lodash 最简单:

_.difference(_.pluck(data, "id"),
    _.pluck(_.pluck(markerArray, "properties"),"id"));

这是一个 lodash 解决方案:

_.reject(data, _.flow(
    _.identity,
    _.property('id'),
    _.partial(_.includes, _.map(markerArray, 'properties.id'))
));

基本上,您想使用 reject() to remove the unwanted items from data (by creating a copy, not by modifying the original). We use flow() 构建决定拒绝哪些项目的回调函数。这是细分:

  • 传递给 reject() 的回调函数有几个参数——我们只关心第一个。这就是 identity() 所做的,它将第一个参数传递给 flow().
  • 中的下一个函数
  • property() 函数 return 是一个新函数。这个新函数将 return 给定项目的 id 属性。同样,此 id 是下一个 flow() 函数的输入。
  • 然后我们使用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()。如果来自 data 的 id 在此数组中,我们可以将其从结果中删除。