比较对象数组

时间:2017-10-12 15:22:37

标签: javascript arrays object comparison

比较对象数组

 function compare (arr1, arr2){
    //if object key value pair from arr2 exists in arr1 return modified array
    for (let obj of arr2) {
         if(obj.key === arr1.key){
             return obj
        }
     }
 }
 // Should return [{key: 1, name : "Bob", {key: 2, name : "Bill"}]

 compare([{key: 1}, {key: 2}], 
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])

我与具有不同长度和属性的循环对象数组断开连接。我尝试过循环和IndexOf,但由于长度不同,我无法比较这两种数组。我觉得过滤器可能是一个很好的工具,但没有运气。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

从第一个数组(键)创建Set个属性,然后使用set创建Array#filter第二个数组(值):



function compareBy(prop, keys, values) {
  const propsSet = new Set(keys.map((o) => o[prop]));

  return values.filter((o) => propsSet.has(o[prop]));
}

const result = compareBy('key', [{key: 1}, {key: 2}], 
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])

console.log(result);




相关问题