简体   繁体   English

返回 javascript 中 2 个对象之间的匹配元素数组的最高效方法是什么?

[英]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:给定 javascript 中的以下 2 个对象:

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 2 个对象是否包含匹配键

If all keys are different, then a merged object will have as many keys as each object individually.如果所有键都不同,则合并的 object 将具有与每个 object 一样多的键。

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:使用HashMap数据结构方法:

 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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