The function filter() in Javascript

Yoel Macia
The Javascript Adventure
3 min readDec 7, 2019

This useful array method creates a new array with all elements that pass the test implemented by the provided function. If no elements pass the test, an empty array will be returned.

Photo by Simone Hutsch on Unsplash

Let talk about we have an array of objects with subjects name, the score on the first semester and the second semester.

let subjects = [
{
'name' : 'maths',
'score_1' : 5,
'score_2' : 7
},
{
'name' : 'literature',
'score_1' : 9,
'score_2' : 8
},
{
'name' : 'music',
'score_1' : 1,
'score_2' : 6
}
];

Now let´s create a new array of subjects passed in the first semester.

let subjectsPassedFirstSemester = [];for (let i = 0; i < subjects.length; i++) {
if (subjects[i].score_1 >= 5) {
subjectsPassedFirstSemester.push(subjects[i]);
}
}
console.log(subjectsPassedFirstSemester);

Now its time to introduce,

Array.filter(callback, thisValue);

This function have three arguments for the callback (element, index, array)

element -> required, the current element being processed in the array.
index -> Optional, the index of the current element being processed in the array.
array -> Optional, the array filter was called upon.

And thisValue is to use as this when executing callback.

Let´s write the function which creates a new array of subjects with the Array.filter() function:

let subjectsPassedFirstSemester = subjects.filter(subject => {
return subject.score_1 >= 5;
});
console.log(subjectsPassedFirstSemester);

Benefits of using array.filter():

  1. Since you operate with the element of the array, you don´t have to define any index.
  2. You don’t have to create a new array and push elements into it.
  3. Don’t have to create any loop.
  4. Remember always return, otherwise you will get an empty array.

What about the other arguments?

Index → will be print the index of the array, like i in our loop example.

let lastSubjectOfArray = subjects.filter((subject,index) => {
return index > 1;
});
console.log(lastSubjectOfArray);
// { name: 'music', score_1: 1, score_2: 6 } ]

Array → will be print the array of the current element belongs to, in this particular case 3 times.

let array = subjects.map((subject,index,array) => {
return array;
});
console.log(array);
//
[
{ name: 'maths', score_1: 5, score_2: 7 },
{ name: 'literature', score_1: 9, score_2: 8 },
{ name: 'music', score_1: 1, score_2: 6 }
]

thisValue -> Does nothing when using an arrow function its because, arrow functions cannot be bound. A this value is a special object which is related with the execution context of the function. For example.

var myObject = { name: 'myObject' };[1,2].map(function(item) { 
console.log(item); // 1, 2
console.log(this === myObject); // true
}, myObject)

--

--

Yoel Macia
The Javascript Adventure

Writing daily about Javascript. Creator of the publication The Javascript Adventure.