When should you use array methods (map, filter, reduce)?

Array methods such as map, filter, and reduce are powerful tools in JavaScript for handling and processing arrays. Here's when to use each of them:

  • map: Use map when you need to transform each element in an array and create a new array with the transformed elements. For instance, if you want to double each number in an array.
  • filter: Use filter when you want to create a new array containing only the elements that meet a specific condition. For example, getting all even numbers from an array.
  • reduce: Use reduce when you want to reduce an array to a single value, such as the sum of all the elements in the array.

Examples:

Here's how you can use these methods:

// Example using map const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled); // Output: [2, 4, 6, 8] // Example using filter const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4] // Example using reduce const sum = numbers.reduce((accumulator, current) => accumulator + current, 0); console.log(sum); // Output: 10

JavaScript Array methods Map Filter Reduce Array manipulation