как работает filter in javascript

The filter() method in JavaScript is used to create a new array with all the elements that pass a certain condition. It takes a callback function as its argument and applies that function to each element of the array.

Here is the syntax for using filter():

index.tsx
const newArray = array.filter(callbackFunction);
49 chars
2 lines

The callbackFunction takes three arguments:

  1. element (required): The current element being processed in the array.
  2. index (optional): The index of the current element being processed.
  3. array (optional): The array on which filter() was called.

The callbackFunction should return true or false. If it returns true, the element is included in the new array, otherwise, it is skipped.

Here's an example that demonstrates the usage of filter():

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

const evenNumbers = numbers.filter((element) => {
  return element % 2 === 0;
});

console.log(evenNumbers); // Output: [2, 4]
161 chars
8 lines

In this example, filter() is used to create a new array evenNumbers that contains only the even numbers from the numbers array.

Note that filter() does not modify the original array. It returns a new array.

I hope this helps!

related categories

gistlibby LogSnag