Back to Homepage
Wednesday 7 August 2024
6

How to filter in JavaScript

Steps to Filter an Array in JavaScript

Need to filter an array in JavaScript? Follow these easy steps:

1. Create an Array:

  • Define an array with elements you want to filter:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

2. Apply the Filter Method:

  • Use the filter() method to create a new array with elements that match the criteria:
const evenNumbers = numbers.filter(number => number % 2 === 0);

3. Check the Result:

  • Output the filtered array to verify the results:
console.log(evenNumbers); // [2, 4, 6, 8, 10]

4. Filter with Custom Criteria:

  • You can filter based on any condition. For example, filtering strings by length:
const words = ['apple', 'banana', 'cherry', 'date'];
     const longWords = words.filter(word => word.length > 5);
     console.log(longWords); // ['banana', 'cherry']
Share:
Created by:
Author photo

Jorge García

Fullstack developer