3 回答
TA贡献1818条经验 获得超11个赞
这是我的解决方案。
const matches = Object.keys(myFruit).filter(key => key in theirFruit); console.log(matches); // will output ['apple']
TA贡献1890条经验 获得超9个赞
2 个对象是否包含匹配键
如果所有键都不同,则合并的对象将具有与每个对象一样多的键。
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))
TA贡献1862条经验 获得超7个赞
使用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']
添加回答
举报