Mastering JavaScript's Array Powerhouses: forEach, map, filter, reduce, spread, and rest

thenamerahulkr

Rahul Kumar

Posted on November 23, 2024

Mastering JavaScript's Array Powerhouses: forEach, map, filter, reduce, spread, and rest

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:

  1. Filtering Even Numbers:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]

  1. Creating a New Array with Squared Numbers:

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]

  1. Summing Array Elements:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator +
currentValue, 0);
console.log(sum); // Output: 15
 

  1. Flattening a Nested Array:

const nestedArray = [[1, 2], [3, 4], [5]];
const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // Output: [1, 2, 3, 4, 5]

💖 💪 🙅 🚩
thenamerahulkr
Rahul Kumar

Posted on November 23, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related