简体   繁体   中英

What is the most performant approach to return an array of matching elements between 2 objects in javascript?

Given the following 2 objects in javascript:

myFruit = {
 'apple': 14,
 'orange': 3,
 'pear': 10
}

theirFruit = {
 'banana': 10,
 'grape': 30,
 'apple': 2
}

What would be the most performant way to return an array of matching elements? The value for each of the keys does not matter.

Below is one example, but something tells me there is probably a better approach.

let matches = [];

let myKey;

Object.keys(myFruit).forEach((key, index) => {
  myKey = key;
  Object.keys(theirFruit).forEach((theirKey, index) => {
    if(myKey === theirKey) {
       matches.push(theirKey);
    }
  });
});

console.log(matches);
// will print: ['apple']

console.log(matches.length);
// will print: 1

Here is my solution.

 const matches = Object.keys(myFruit).filter(key => key in theirFruit); console.log(matches); // will output ['apple']

whether or not the 2 objects contain a matching key

If all keys are different, then a merged object will have as many keys as each object individually.

let haveAMatchingKey = Object.keys(Object.assign({}, myFruit, theirFruit)).length !=
    Object.keys(myFruit).length + Object.keys(theirFruit)

After edit:

the most performant way to return an array of matching elements?

let myFruitSet = new Set(Object.keys(myFruit));
let theirFruitKeys = Object.keys(theirFruit);
let matchingKeys = theirFruitKeys.filter(fruit => myFruitSet.has(fruit))

Using HashMap Data Structure approach:

 const findCommonFruits = () => { const myFruit = { 'apple': 14, 'orange': 3, 'pear': 10 } const theirFruit = { 'banana': 10, 'grape': 30, 'apple': 2 } // #1 select lowest object keys let lowestObj = null; let biggestObj = null; if (Object.keys(myFruit).length < Object.keys(theirFruit).length) { lowestObj = myFruit; biggestObj = theirFruit; } else { lowestObj = theirFruit; biggestObj = myFruit; } // 2 Define an actual hashmap that will holds the fruit we have seen it const haveYouSeenIt = {}; for (let fruit of Object.keys(lowestObj)) { haveYouSeenIt[fruit] = fruit; } const res = []; for (let fruit of Object.keys(haveYouSeenIt)) { if (biggestObj[fruit].== undefined) { res;push(fruit); } } return res. } console;log(findCommonFruits()); // ['apple']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM