根据某些给定的首选项过滤和返回数组中的元素



假设我有两个数组 - 一个作为顺序的首选项,另一个作为数据集,我想从数据集中返回第一个元素匹配第一个匹配的首选项。

例如

const userPref = ['banana', 'apple', 'peach'];
const givenFruits = [
{ name: 'apple', color: 'red' },
{ name: 'orange', color: 'orange' },
{ name: 'pear', color: 'yellow' },
{ name: 'cherry', color: 'red' },
{ name: 'grape', color: 'red' },
{ name: 'peach', color: 'red' },
{ name: 'coconut', color: 'brown' }
];
function findFavFruit() {
userPref.forEach((pref) => {
givenFruits.forEach((fruit) => {
if(pref === fruit.name) {
return fruit;
}
});
});
}
console.log('findFavFruit(): ' + JSON.stringify(findFavFruit(), null, 2));

这总是返回undefined.它应该只返回apple因为它是用户第一个匹配的首选项,并且首先在给定的水果中找到。

我在上面的代码中做错了什么?在Javascript中是否有一种更清洁的方法(避免双重forEach(?

您可以使用以下命令循环给定的水果...并使用 Array.include 来测试当前水果是否在最喜欢的水果数组中。

例:

function findFavoriteFruit(preferences, arrayOfFruits) {
for (let fruit of arrayOfFruits) {
if (preferences.includes(fruit.name)) {
return fruit;
}
}
}
const userPref = ['apple', 'banana', 'peach'];
const givenFruits = [
{ name: 'apple', color: 'red' },
{ name: 'orange', color: 'orange' },
{ name: 'banana', color: 'yellow' },
{ name: 'pear', color: 'yellow' },
{ name: 'cherry', color: 'red' },
{ name: 'grape', color: 'red' },
{ name: 'peach', color: 'red' },
{ name: 'coconut', color: 'brown' }
];
const favoriteFruit = findFavoriteFruit(userPref, givenFruits);
console.log(favoriteFruit);

正如您在此处看到的,此实现是最快的(与其他答案相比(。

选择要userPref数组中的第一个元素fruit.name.find()函数中进行比较,返回结果。

若要仅返回属性值(例如"name"(,可以将属性作为字符串传递给函数,并使用括号表示法引用和返回属性

const userPref = ['apple', 'banana', 'peach'];
const [preference] = userPref;
const givenFruits = [
{ name: 'apple', color: 'red' },
{ name: 'orange', color: 'orange' },
{ name: 'banana', color: 'yellow' },
{ name: 'pear', color: 'yellow' },
{ name: 'cherry', color: 'red' },
{ name: 'grape', color: 'red' },
{ name: 'peach', color: 'red' },
{ name: 'coconut', color: 'brown' }
];
function findFavFruit(pref, prop, arr) {
return arr.find(fruit => pref === fruit[prop])[prop];
}
let res = findFavFruit(preference, "name", givenFruits);
console.log(res);

当然,您应该提供一些检查给定的键是否存在,但这是基本的:

(givenFruits.find((v)=>{return v.name == userPref[0]})).name

不知道为什么循环访问userPref,如果你只需要第一个密钥。

以上所有解决方案都是正确的,我只是想澄清您的代码的问题是什么。见下文:

function findFavFruit() {
let userFruit;
userPref.forEach((pref) => {
givenFruits.forEach((fruit) => {
if(pref === fruit.name) {
userFruit = fruit;
}
});
});
return userFruit;
}

如果发现水果,这将返回水果,如果没有,这将返回未定义。

最新更新