JavaScript Filter Arrays – How to filter arrays in JavaScript

4 years ago Lalit Bhagtani 0

JavaScript Filter Arrays

In this tutorial, we will learn about how to filter arrays in JavaScript.

JavaScript Filter Arrays

Array Filter Method :-

JavaScript Array object contains a filter method, which can be used to filter the elements of an array. This method takes one predicate function which tests each element of the array and keeps the element if the test returns true and drop it if it returns false. It returns the new array containing all the element which were passed in the test.

Syntax :-

newArray = array.filter(callback(element[, index, [array]])[, this])

Where 
callback : It is a predicate function which test each element of the array.
 It returns true to keep the element and false to drop it.

It accepts three arguments:
1. element : The current element being processed in the array.
2. index (Optional) : The index of the current element being processed in the array.
3. array (Optional) : The array on which filter is called on.
4. this  (Optional) : Value to use as this when executing callback.

Let’s see the example :- 

<script>
let array = [1, 5, 8, 10, 12, 15, 16];

let newArray = array.filter((element) => element%5 === 0);

console.log(newArray);
</script>

References :- 

  1. Array Filter Docs

If you liked it, please share your thoughts in comments section and share it with others too.