Filter( ) in JavaScript
Filter() is a method in JavaScript that can effortlessly provide filtered output data(in the form of array) by processing an array
Here's the syntax of the filter()
method:
let newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
In this syntax:
newArray: This is the new array that will be returned by the filter() method.
arr
: This is the original array on which thefilter()
method was called.callback
: This is a function that tests each element of the array. Returntrue
to keep the element,false
otherwise. It accepts three arguments:element
: The current element being processed in the array.index
(optional): The index of the current element being processed in the array.array
(optional): The arrayfilter()
was called upon.
thisArg
(optional): Value to use asthis
when executingcallback
.
Here's a simple example:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredNumbers = numbers.filter((number) => number % 2 === 0);
console.log(filteredNumbers); // Output: [2, 4, 6, 8, 10]
In this example, the filter()
method is used to filter out the even numbers from the numbers
array. The new evenNumbers
array is then logged to the console.
Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.
Twitter: https://twitter.com/Diwakar_766
GitHub: https://github.com/DIWAKARKASHYAP
Portfolio: https://diwakar-portfolio.vercel.app/