javascript

Different methods to filter a JavaScript array of objects

Feb 11, 2020

One of the common operations when working with arrays is filtering them down. I will go through a few different ways that we can filter out a JavaScript array.

One of the common operations when working with arrays is filtering them down. For example, given an array of student scores, we want to select the ones that have more than 50.

let students = [
    {name: 'Gary', score: 55},
    {name: 'John', score: 22},
    {name: 'Chris', score: 89},
    {name: 'Hudson', score: 45},
    {name: 'Jeremie', score: 92}
];

In this post, I will go through a few different ways that we can filter out a JavaScript array.

Using for loops

The most basic way to filter the array is using good-old fashioned loops. In the example below, we will want to get the students with scores higher than 50:

let passedStudents = [];
for (let i = 0; i < students.length; i++) {
    if (students[i].score > 50) {
        passedStudents.push(students[i]);
    }
}
console.log(passedStudents);

Using the filter method

Array also comes with the filter method that returns a new array of the filtered results. It accepts a callback to test if a element should belong to the filtered array.

var passedStudents = students.filter(function (e) {
    return e.score > 50;
});
console.log(passedStudents);

In ES6 you can reduce the above code even further by using arrow functions:

var passedStudents = students.filter(e => e.score > 50);
console.log(passedStudents);

With this method, we might need to create a polyfill to cater for browsers that does not support this method - eg IE. More information about the polyfill here

Using while loops

let index = 0;
let passedStudents = [];
const numberOfStudents = students.length;

while (index < numberOfStudents) {

    if (students[index].score > 50) {
        passedStudents.push(students[index]);
    }

    index++;
}

Hope this is a useful reference.