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
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
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
when you want to reduce an array to a single value, such as the sum of all the elements in the array.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
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?