JavaScript arrays have a filter()
method that let you create a new array containing just the elements you need. Here are 5 common examples that demonstrate how to use filter()
.
The filter()
function takes a callback, and returns a new array containing just the elements that callback
returned truthy for. This means you can use filter()
to filter arrays of primitives, like finding all elements in an array of strings that start with “A”, or finding all even numbers in an array:
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
nums.filter(function isEven(num) {
return num % 2 === 0;
}); // [2, 4, 6, 8, 10]
#javascript #developer