搜索对象和数组定位匹配的最有效方法

Most efficient way to search through an object and array locating match

我有 2 个 object/arrays:

var objA = {
    Red Chair : "DC10291",
    USBDongle : "USKI82322",
}

var arrayB = [
   {
       field: "Yellow Banana",
       id: "Yellow Banana"
   },
   {
       field: "Red Chair",
       id: "Red Chair"
   },
   {
       field: "Garden",
       id: "Garden"
   }
]

我想做的是,如果 KEY 来自 objA,例如Red Chair,出现在 arrayB 中,然后从 arrayB 中删除它。

我已经这样做了:

var arrayClone = _.cloneDeep(arrayB);
var removeThese = [];

Object.keys(arrayClone).forEach(function(p) {
    removeThese.push(p)
});


removeThese.forEach(function(remove) {
    arrayB.forEach(function(item) {
        if(item.id === remove) {
            delete objA[remove];
        }
    });
 });

以上按预期工作,但是这是最有效的吗?我问的原因是因为在数组循环中循环 throuhg 和数组感觉不是最佳实践?并且会对性能产生影响

你可以像这样简单地过滤它

_.filter(arrayB, obj => !objA.hasOwnProperty(obj.field))
// [ { field: 'Yellow Banana', id: 'Yellow Banana' },
//  { field: 'Garden', id: 'Garden' } ]

这使用了 ES2015 的箭头函数语法。你可以用像这样的普通函数写同样的东西

arrayB.filter(function(obj) {
  return !objA.hasOwnProperty(obj.field);
});
// [ { field: 'Yellow Banana', id: 'Yellow Banana' },
//  { field: 'Garden', id: 'Garden' } ]

我们基本上过滤掉了所有 field 值为 objA 中的键的对象。

如果您想保留原始 arrayB 并根据您的条件获得它的简化版本,那么 Array.prototype.reduce() 可以使用 O(n) 时间复杂度来实现。但是,如果您想就地执行此操作,那么 Array.prototype.reduceRight() 的时间复杂度为 O(n)。

var objA = {
    "Red Chair" : "DC10291",
    "USBDongle" : "USKI82322",
},

 arrayB = [
   {
       field: "Yellow Banana",
       id: "Yellow Banana"
   },
   {
       field: "Red Chair",
       id: "Red Chair"
   },
   {
       field: "Garden",
       id: "Garden"
   }
],

 arrayC = arrayB.reduce((p,c) => !objA[c.field] ? p.concat(c) : p, []);
 console.log(arrayC);
 arrayB.reduceRight((p,c,i,a) => (p[c.field] && a.splice(i,1),p),objA);
 console.log(arrayB);