0

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.