Home > Net >  Filter one array using another
Filter one array using another

Time:10-01

I am trying to write a function that prints out a list of all courses with a passing grade but cant't figure out how. How may I implement that? (The minimum passing grade is 5.)

input:

courses = [Math, Geography, Chemistry]
grades = [7, 3, 5]

The grades[0] grade corresponds to the courses[0] course and so on.

Desired output:

Passed = Math, Chemistry

I have tried using filter but it didn't work, though I was using it wrong since the filter parameter is not an index.

It was something like

courses.filter((x) => grades[x] >= 5)

CodePudding user response:

The second parameter to the filter predicate (like most of the closures that can be applied to arrays) is the index of the element.

Use that to index the grades array...

const courses = ['Math', 'Geography', 'Chemistry'];
const grades = [7, 3, 5];

const passedCourses = courses.filter((_, index) => grades[index] > 4)
console.log(passedCourses);

CodePudding user response:

You are missing index please add index parameter in filter.

let courses=['Math', 'Geography', 'Chemistry']; 
let grades=[7,3,5]; 
let result=courses.filter((item,index)=> 
{ 
 if(grades[index] > 4){ 
   return item; 
 }
})
console.log(result)

CodePudding user response:

filter comes with some optional parameters you can take advantage of.

The "current index" of the iteration is the second one. Use that index to get the required element from grades.

const courses = ['Math', 'Geography', 'Chemistry'];
const grades = [7, 3, 5];

const filtered = courses.filter((_course, index)=> grades[index] >= 5);

console.log(filtered);

  • Related