![](/img/trans.png)
[英]Javascript: Array of objects to object containing arrays of values - most performant way?
[英]What is the most performant approach to return an array of matching elements between 2 objects in javascript?
給定 javascript 中的以下 2 個對象:
myFruit = {
'apple': 14,
'orange': 3,
'pear': 10
}
theirFruit = {
'banana': 10,
'grape': 30,
'apple': 2
}
返回匹配元素數組的最高效方式是什么? 每個鍵的值無關緊要。
下面是一個例子,但有些事情告訴我可能有更好的方法。
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
這是我的解決方案。
const matches = Object.keys(myFruit).filter(key => key in theirFruit); console.log(matches); // will output ['apple']
2 個對象是否包含匹配鍵
如果所有鍵都不同,則合並的 object 將具有與每個 object 一樣多的鍵。
let haveAMatchingKey = Object.keys(Object.assign({}, myFruit, theirFruit)).length !=
Object.keys(myFruit).length + Object.keys(theirFruit)
編輯后:
返回匹配元素數組的最高效方式?
let myFruitSet = new Set(Object.keys(myFruit));
let theirFruitKeys = Object.keys(theirFruit);
let matchingKeys = theirFruitKeys.filter(fruit => myFruitSet.has(fruit))
使用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.