Filtering array in JavasScript
The filter() method does not execute the function for empty elements and does not change the original array.
array.filter(function(currentValue, index, arr), thisValue)
- callback(required): This is a callback method that holds the function to be called for each element of the array.
- element(required): This is a value of the elements being processed currently.
- index(optional): This param is used for the index of the current element in the array starting from 0.
- arr(optional): It contains the complete array on which
- thisValue(optional):: it holds the context to be passed as this is to be used while executing the callback function.
Let’s demonstrate some examples of filter arrays. I am creating the below script to select only the even numbers from an array of numbers:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const even_numbers = numbers.filter(number => number % 2 === 0); console.log(evenNumbers);
in the above code :
- We have initialized the array.
- Applied filter() methods, that create a new array called “even_numbers” by testing each element in the “numbers” array using the callback function that checks whether the number is even.
- The result is a new array containing only the even numbers.
[2, 4, 6, 8, 10]
You can also apply any conditional operators :
const fruits = ["apple", "banana", "orange", "kiwi", "pear"]; const shortFruits = fruits.filter(fruit => fruit.length < 5); console.log(shortFruits);
in the above code, the callback function checks whether the length of the string is less than 5. The result is a new array containing only the fruits with a length less than 5.