Skip to main content

Iterating Over Arrays in JavaScript

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you'll learn various ways to iterate over arrays in JavaScript.

The forEach() Method

The forEach() method executes a provided function once for each array element.

const numbers = [45, 4, 9, 16];
numbers.forEach(value => console.log(value)); // Logs each item to console

// Output:
45
4
9
16

The function passed to forEach() accepts three parameters:

  • value - The value of the current item.
  • index - The index of the current item.
  • array - The array being iterated over.

Using All Three Parameters

const numbers = [45, 4, 9, 16];
numbers.forEach((value, index, array) => {
   console.log(`Index: ${index}, Value: ${value}, Array: [${array}]`);
});

// Output:
Index: 0, Value: 45, Array: [45,4,9,16]
Index: 1, Value: 4, Array: [45,4,9,16]
Index: 2, Value: 9, Array: [45,4,9,16]
Index: 3, Value: 16, Array: [45,4,9,16]

The map() Method

The map() method creates a new array by applying a function to each element of the original array.

const numbers = [45, 4, 9, 16, 25];
const doubled = numbers.map(value => value * 2);
console.log(doubled);

// Output:
[90, 8, 18, 32, 50]

Separate Function

const numbers = [45, 4, 9, 16, 25];
function doubleValue(num) {
   return num * 2;
}
const doubledNumbers = numbers.map(doubleValue);
console.log(doubledNumbers);

// Output: [90, 8, 18, 32, 50]

The flatMap() Method

Introduced in ES2019, the flatMap() method processes each element and flattens the result.

const values = [10, 20, 30, 40, 50, 60];
const tripled = values.flatMap(num => [num * 3]);
console.log(tripled);

// Output: [30, 60, 90, 120, 150, 180]

The filter() Method

The filter() method creates a new array containing elements that meet a specified condition.

const values = [30, 7, 12, 22, 50];
const greaterThan20 = values.filter(num => num > 20);
console.log(greaterThan20);

// Output: [30, 22, 50]

The reduce() Method

The reduce() method accumulates array elements into a single value.

const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce((total, value) => total + value);
console.log(sum);

// Output: 99

Using an Initial Value

const sumWithInitial = numbers.reduce((total, value) => total + value, 100);
console.log(sumWithInitial);

// Output: 199

The reduceRight() Method

Similar to reduce(), but processes elements from right to left.

const numbers = [45, 4, 9, 16, 25];
let sumRight = numbers.reduceRight((total, value) => total + value);
console.log(sumRight);

// Output: 99

The every() Method

Checks if all elements satisfy a condition.

const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(value => value > 18);
console.log(allOver18);

// Output: false

The some() Method

Checks if at least one element satisfies a condition.

const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(value => value > 18);
console.log(someOver18);

// Output: true

The Array.from() Method

Creates an array from an iterable object.

const letters = Array.from("XYZ123");
console.log(letters);

// Output: ['X', 'Y', 'Z', '1', '2', '3']

The keys() Method

Returns an iterator for the indices of an array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
for (let key of keys) {
   console.log(key);
}

// Output:
0
1
2
3

The entries() Method

Returns an iterator for key/value pairs.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const entries = fruits.entries();
for (let entry of entries) {
   console.log(entry);
}
// Output:
[0, 'Banana']
[1, 'Orange']
[2, 'Apple']
[3, 'Mango']

The with() Method

Modifies an array while keeping the original unchanged.

const months = ["Jan", "Feb", "Mar", "Apr"];
const updatedMonths = months.with(2, "March");
console.log(updatedMonths);

// Output: ['Jan', 'Feb', 'March', 'Apr']

The Spread Operator

Combines multiple arrays.

const firstHalf = ["Jan", "Feb", "Mar"];
const secondHalf = ["Apr", "May", "Jun"];
const fullYear = [...firstHalf, ...secondHalf];
console.log(fullYear);

// Output: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']

Questions & Answers