To filter elements of an array based on a condition in JavaScript, you can use the filter method.
In this example,
numbers
containing integers.filter
method with a callback function to filter out even numbers.const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log('Even Numbers:', evenNumbers);
Even Numbers: [ 2, 4, 6, 8, 10 ]
In this example,
words
containing strings.filter
method with a callback function to filter strings by their length.const words = ['apple', 'banana', 'cherry', 'date', 'fig'];
const filteredWords = words.filter(word => word.length > 5);
console.log('Filtered Words:', filteredWords);
Filtered Words: [ 'banana', 'cherry' ]
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in JavaScript language with well detailed examples.