array filter in javascript

To filter arrays in JavaScript, we can use the filter() method. The filter() method creates a new array with all the elements that pass the provided function's test. Here is an example usage of the filter() method:

index.tsx
const numbers = [1, 2, 3, 4, 5];

const filteredNumbers = numbers.filter(function(number) {
  return number > 2;
});

console.log(filteredNumbers); // [3, 4, 5]
161 chars
8 lines

In the above example, we first define an array called numbers. We then call the filter() method on the numbers array. Inside the filter() method, we provide a function that takes in each element of the array, one at a time. The function checks whether each element is greater than 2. If an element is greater than 2, it is included in the filteredNumbers array; otherwise, it is excluded.

This is an example of functional programming, where we define a function that takes in each element of the array and returns a boolean indicating whether the element should be included in the filtered array or not.

gistlibby LogSnag