In JavaScript, an array is a collection of comma-separated elements. In this shot, we'll learn how to filter elements in the array with certain criteria.
We can use the method filter()
on the array to filter the elements. It accepts a function as a parameter and returns a filtered array.
array.filter(element=>{return //condition})
//given numbersnums = [1,2,3,4,5,6,7,8,9,10]//filter even numbersevenNums = nums.filter( ele => {return ele % 2 == 0})//display even numbersconsole.log(evenNums)
nums
.filter
method to filter the even numbers on the array, nums
.filter
condition, which is to check if the current element ele
is even or not. If it is even, then the method returns it.evenNums
.