forEach: Iterating Over Elements
The forEach method iterates over each element in an array, executing a provided callback function for each element.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
console.log(num);
});
map: Transforming Elements
The map method creates a new array by applying a provided function to each element of the original array.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
filter: Selecting Elements
The filter method creates a new array containing only the elements that pass a test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output:
[2, 4]
reduce: Accumulating Values
The reduce method reduces an array to a single value by applying a function against an accumulator and each element in the array.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator
currentValue, 0);
console.log(sum); // Output: 15
spread Operator (...): Expanding Elements
The spread operator expands an iterable (array, string, object) into its individual elements.
const numbers = [1, 2, 3];
const newArray = [...numbers, 4, 5];
console.log(newArray); // Output: [1, 2, 3, 4, 5]
rest Operator (...): Gathering Elements
The rest operator collects remaining elements into an array.
function sum(...numbers) {
return numbers.reduce((total, num) => total num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Practical Examples:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator
currentValue, 0);
console.log(sum); // Output: 15
const nestedArray = [[1, 2], [3, 4], [5]];
const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]
The above is the detailed content of Mastering JavaScripts Array Powerhouses: forEach, map, filter, reduce, spread, and rest. For more information, please follow other related articles on the PHP Chinese website!