Warm tip: This article is reproduced from stackoverflow.com, please click
arrays javascript jquery

Filter array dynamically based on other array in jQuery

发布于 2020-03-27 10:24:33

I'm having trouble solving this situation where I need to filter an array based on the key values of another array. It might be quite easy but I can't catch the proper key value pairs.

I have this array of marks:

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

And another array of tags with the same key names:

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

Now I need to filter tags array if the marks are >65 in marks array and the expected result is:

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

Or even better if it is:

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

What I have tried so far:

filteredTags = []
$.each(marks, function(ind, val) {
  if (val > 60){
    filteredTags = tags.filter(function(i,v) {
      return (i == ind)
  }
})
Questioner
sohal07
Viewed
88
MauriceNino 2019-07-03 22:47

Would be easier with arrays, but this code should work:

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