How to filter an array with certain criteria in JavaScript

Overview

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.

Syntax

array.filter(element=>{
return //condition
})

Example

//given numbers
nums = [1,2,3,4,5,6,7,8,9,10]
//filter even numbers
evenNums = nums.filter( ele => {
return ele % 2 == 0
})
//display even numbers
console.log(evenNums)

Explanation

  • Line 2: We declare and initialize the array of numbers, nums.
  • Line 5: We use the filter method to filter the even numbers on the array, nums.
  • Line 6: We provide the filter condition, which is to check if the current element ele is even or not. If it is even, then the method returns it.
  • Line 10: We display the array that has even numbers, evenNums.

Free Resources