gpt4 book ai didi

javascript - 基于jQuery中的其他数组动态过滤数组

转载 作者:行者123 更新时间:2023-11-30 13:57:53 26 4
gpt4 key购买 nike

我在解决这种情况时遇到了麻烦,我需要根据另一个数组的键值来过滤一个数组。这可能很容易,但我无法捕捉到正确的键值对。

我有这个标记数组:

marks = {
eng : 90,
maths : 50,
phy : 60,
chem : 75,
bio : 85,
}

还有另一个具有相同键名的标签数组:

tags = {
eng : 'English',
maths : 'Maths',
phy : 'Physics',
chem : 'Chemistry',
bio : 'Biology',
}

现在我需要过滤 tags 数组,如果 marks 数组中的标记是 >65 并且预期结果是:

filteredTags = {
eng : 'English',
chem : 'Chemistry',
bio : 'Biology',
}

如果是,甚至更好:

filteredTags = ['English', 'Chemistry', 'Biology']

到目前为止我尝试了什么:

filteredTags = []
$.each(marks, function(ind, val) {
if (val > 60){
filteredTags = tags.filter(function(i,v) {
return (i == ind)
}
})

最佳答案

使用数组会更容易,但这段代码应该可以工作:

let marks = {
eng : 90,
maths : 50,
phy : 60,
chem : 75,
bio : 85,
}

let tags = {
eng : 'English',
maths : 'Maths',
phy : 'Physics',
chem : 'Chemistry',
bio : 'Biology',
}

function getTagsWithMarksAbove(num) {
let result = [];

for(prop in marks) { // Iterate over the properties of the marks object
if(marks[prop] > num) // Check if mark is above the specified number
result.push(tags[prop]); // Add value of tags property with the same name to result array
}

return result;
}
console.log(getTagsWithMarksAbove(65))

关于javascript - 基于jQuery中的其他数组动态过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com