reduce array of objects on pass variable in javascript

In JavaScript, you can use the reduce() method to reduce an array of objects based on a passed variable. The reduce() method applies a function to each element in the array and returns a single output value.

Here's an example of how to use reduce() to reduce an array of objects based on a passed variable:

index.tsx
const students = [
  { name: "Bob", grade: 80 },
  { name: "Alice", grade: 90 },
  { name: "John", grade: 75 },
  { name: "Jane", grade: 95 }
];

const passGrade = 85;

const passedStudents = students.reduce((accumulator, currentValue) => {
  if (currentValue.grade >= passGrade) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(passedStudents);
382 chars
18 lines

In this example, we have an array of student objects with their name and grade. We want to reduce this array to only include the students who passed (those with a grade greater than or equal to passGrade, which in this case is set to 85).

We pass an initial value of an empty array [] to the reduce method as the second argument. We then apply a function to each student object in the array. If the student's grade is greater than or equal to passGrade, we add that student object to the accumulator array. Finally, we return the accumulator array.

The console.log() statement outputs the resulting array of passed students, which will be:

index.tsx
[
  { name: "Alice", grade: 90 },
  { name: "Jane", grade: 95 }
]
66 chars
5 lines

gistlibby LogSnag