compare array of objects

試著忘記壹切 提交于 2021-02-08 11:00:46

问题


Compare Array of Objects

 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"}])

I am having a disconnect with looping arrays of objects with different lengths and properties. I have tried looping and IndexOf but due to different lengths, I cannot compare the two arrays that way. I feel like a filter might be a good tool but have had no luck. Any thoughts?


回答1:


Create a Set of properties from the 1st array (the keys), and then Array#filter the 2nd array (the values) using the set:

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);


来源:https://stackoverflow.com/questions/46713350/compare-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!