JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How does the Array.filter() method work?

Asked on Jul 31, 2024

Answer

The Array.filter() method creates a new array with all elements that pass the test implemented by the provided function. It does not modify the original array.
<!-- BEGIN COPY / PASTE -->
        const numbers = [1, 2, 3, 4, 5];
        const evenNumbers = numbers.filter(number => number % 2 === 0);

        console.log(evenNumbers); // Output: [2, 4]
        <!-- END COPY / PASTE -->
Additional Comment:
  • The filter method takes a callback function as an argument.
  • The callback function is called once for each element in the array.
  • If the callback returns true, the element is included in the new array.
  • The original array remains unchanged.
✅ Answered with JavaScript best practices.
← Back to All Questions