All JavaScript arrays have a built-in function .filter
that allows you to filter certain elements and return a new array.
To filter a JavaScript array, you need to write a function that will determine the filtering rule.
Letβs imagine we have an array of strings:
const arr = ['pine', 'apple', 'pineapple', 'ball', 'roll'];
And we want to filter all string that are longer than 5 characters.
We call arr.filter
and pass in an anonymous arrow funtion as an argument. This function will be called for every element of the array arr
.
If it returns true
, the element of the array will be included in the result. If false
β it will be left out.
const longWords = arr.filter(item => item.length > 5);
console.log(longWords); // ['pineapple']
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!