JavaScript ES6 Filter

The filter is the same as the map, but if the function applied here returns true, then it will move to the new array, or if the function returns false then that item will not be in the array.

 

Suppose I want to extract only the odd numbers from the following array and place them in the new array:

 

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, by applying a filter method, I can simplify it

 

var newArr = arr.filter(function(item) {
return item % 2 == 0
})

Functions are assigned to each item. And the one that returns true here is the new array. And the one that returns false is not in the new array.


You can also call here with an anonymous function or an external function, just like a map. View the Result:

  • Released On:
    04-10-2024
  • Tags:
    javascript