Array Manipulation Using JavaScript Filter Method


In this short tutorial, you’ll learn about Array manipulation using JavaScript filter method. As the name itself implies, the filter method is used to filter an array based on a particular condition.

Other tutorials in JavaScript Array series.

Understanding JavaScript Filter Method

Assuming that you have a list of students with name and age. Let’s see how you can get the list of students with age greater than 10.

What you’ll basically do is iterate over the list of the students and check for age greater than 10. The students with age greater than 10 will be moved to a separate array and you have the filtered array. Here is how the code looks:

let students = [
    { "first_name": "Hari", "age": 13 },
    { "first_name": "Suriel", "age": 12 },
    { "first_name": "Roy", "last_name": 10 }
];

let filtered_students = []
for(let i = 0;i < students.length; i++){ if(students[i]["age"] > 10){
        filtered_students.push(students[i])
    }
}

console.log(filtered_students);

/* Output
[ 
  { first_name: 'Hari', age: 13 },
  { first_name: 'Suriel', age: 12 }
]
*/

Now let’s try to implement the above filtering process using JavaScript filter method.

Using the JavaScript filter method you don’t need to use the for loop to iterate over each element inside the array. Nor do you need to maintain a separate array for pushing the filtered objects.

JavaScript filter method when applied to an array returns a list of filtered items which satisfy the filter condition.

Let’s implement the above code using the JavaScript filter method. Here is how the code looks:

let students = [
    { "first_name": "Hari", "age": 13 },
    { "first_name": "Suriel", "age": 12 },
    { "first_name": "Roy", "last_name": 10 }
];

// es5
var filtered_students = students.filter(function(student){
    return student.age > 10
});

// es6
let filtered_students = students.filter(student => {
    return student.age > 10
});

console.log(filtered_students);

/* Output
[ 
  { first_name: 'Hari', age: 13 },
  { first_name: 'Suriel', age: 12 }
]
*/

In the above code, the student object which satify the condition specified in the callback function would be returned, hence creating the filtered array.

How Is It Different From JavaScript map Method ?

JavaScript map and filter are both array manipulation methods serving different purposes.

JavaScript map returns a new array based on the modifications applied on the original array elements without filtering out anything from the array.

Filter on the other hand filters out items from the array based on the filter condition and returns a new array.

Wrapping It Up

In this tutorial, you learnt how to do Array manipulation using JavaScript filter method. Do let us know if you have any doubts or suggestions in the comments below.

Understanding JavaScript Map Method For Array Manipulation

Understanding JSON Array In JavaScript