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:
✅ Answered with JavaScript best practices.- 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.
Recommended Links:
← Back to All Questions