JavaScript Array filter() Method

JavaScript Array filter() Method

The JavaScript filter method can be used to filter elements in an array. We have to pass a custom function (callback function) to this method as parameter and this function receives each array elements to process.

var allAges = [28, 33, 16, 40];
function checkAge(age) {
      if(age > 30)
          return true;
}
var agesAbove30 = allAges.filter(checkAge);
console.log(agesAbove30)
//console output will be [33, 40]

If the callback function returns true then the array element get assigned to the result array. See the above example, each array element get passed to the callback function 'checkAge' and if its value is greater than 30 then the callback function returns true, then the array element get assigned to the 'agesAbove30' array.

We have write the above code in the following way using ES6 syntax.

var allAges = [28, 33, 16, 40];
var agesAbove30 = allAges.filter( age => age > 30);
console.log(agesAbove30)
//console output will be [33, 40]

The JavaScript Array filter() method

filter(function callbackFn(element, index, array) { ..... }, value)

The filter method has two parameters, the callback function and a custom value to the callback function. This custom value can be referenced in callback function using the 'this' keyword.

The callback function receives three parameters, The element value, the element index and array itself.

The following code example logs all the values received in the callback function

var allAges = [100, 200];
function checkAge(elementValue, elementIndex, array) {
      console.log('elementValue = '+ elementValue)
      console.log('elementIndex = '+ elementIndex)
      console.log('array = '+ array)
      console.log('customValue = '+ this)
      console.log('------------------')
}

var customValue = 45
var agesAbove30 = allAges.filter(checkAge, customValue);

/*
Console output would be
elementValue = 100
elementIndex = 0
array = 100,200
customValue = 45
------------------
elementValue = 200
elementIndex = 1
array = 100,200
customValue = 45
------------------
*/