Array Methods (map, filter, reduce)
JavaScript provides powerful array methods that allow you to manipulate and transform arrays in a concise and functional way.
const numbers = [1, 2, 3, 4, 5];
// map: transforms each element of the array
const multiplied = numbers.map(num => num * 2);
console.log(multiplied); // Output: [2, 4, 6, 8, 10]
// filter: filters elements based on a condition
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
// reduce: reduces the array to a single value
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15
In the example above, the map method is used to multiply each element of the numbers array by 2. The filter method is used to filter out even numbers. The reduce method is used to calculate the sum of all numbers in the array.
No comments:
Post a Comment