JavaScript array filter() method creates a new array whose elements satisfy the specified condition. The filter() method accepts a callback function, and this callback function is called for every element of the array. Inside the callback function, you specify the condition. The elements of the existing array that satisfy the condition become a member of the new array. In other words, when you return true from the callback function, then the current element that is being processed becomes a member of the new array. When you return false, then that element won't be considered a member of the new array.
Note: The filter() method does not modify the existing array.
The filter() method has the following form:
let newArray = array.filter(callback, contextArg);
Callback function passed to the filter() method has the following syntax:
function callback(currentElement, index, array){ //return true or false }
It is recommended that you use the arrow function as a callback function.
(currentElement, index, array)=>{ //return true or false }
The callback function accepts three arguments:
currentElement
argument represents the current element that is being processed.index
argument points to the index value of the current element.array
argument is the array on which you are using the filter() method.The contextArg
argument is optional. If you use this
value inside the callback function, then this
will point to the value passed to the contextArg
argument.
Prior to the filter() method, for
loop is used to perform the tasks, which are now performed by the filter() method. Suppose you have an array of integer values, and you want to get even numbers from that array. With the help of a for
loop, you loop through all the elements and filter those divisible by 2.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let newArray = []; for(let i=0; i<numbers.length; i++){ if(numbers[i]%2 === 0){ newArray.push(numbers[i]); } } console.log(newArray);
Output
[2, 4, 6, 8, 10]
Let's rewrite the above code using the filter() method.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let newArray = numbers.filter((number)=>{ if(number%2 === 0){ return true; }else{ return false; } }); console.log(newArray);
Output
[2, 4, 6, 8, 10]
You can also remove parenthesis, braces and return and make the code more concise.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let newArray = numbers.filter(number=>number%2===0); console.log(newArray);
As you can see, the code that involves using a for loop is more verbose. On the other hand, the filter() method makes the code short and concise.
Suppose you want to filter weights that are greater than the average weight of students. Using the reduce() method, you will calculate the total sum of weight and then compute the average weight. After that, with the help of the filter() method, you will get weights that are greater than the average weight.
let marks = [80, 77, 88, 95, 68]; let totalMarks = marks.reduce((acc, cur)=>acc + cur, 0); const averageMarks = totalMarks/marks.length; let marksGreaterThanAvg = marks.filter(mark=>mark>=averageMarks); console.log(marksGreaterThanAvg); console.log(averageMarks);
Output
81.6
When you draw charts in D3.js, you may need to update the graph based on the range of value entered by the user. In that situation, the contextArg argument will be helpful to you.
let range = { lower:100, upper:500 }; let quarterSalesRecord = [ { month:'January', sales:600 }, { month:'February', sales:400 }, { month:'March', sales:500 } ]; function filterSalesRecords(salesRecords){ if(salesRecords.sales >= this.lower && salesRecords.sales <= this.upper){ return true; }else{ return false; } } let salesRecordsInRange = quarterSalesRecord.filter(filterSalesRecords, range); console.log(salesRecordsInRange);
Output
[[object Object] { month: "February", sales: 400 }, [object Object] { month: "March", sales: 500 }]
The range
object has two properties, lower
and upper
. It is passed as the contextArg
argument to the filter() method. You can access it using this
keyword inside the callback function.