温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Filter array dynamically based on other array in jQuery
arrays javascript jquery

javascript - 根据jQuery中的其他数组动态过滤数组

发布于 2020-03-27 11:24:36

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

我有这一系列标记:

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

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

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

现在,tags如果标记>65marks数组中并且期望的结果是:

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)
  }
})

查看更多

查看更多

提问者
sohal07
被浏览
132
MauriceNino 2019-07-03 22:47

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

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))