JS Array Iterations

Loop through arrays with powerful iteration methods

🔄 What are Array Iterations?

Array iterations are methods that let you loop through each element in an array. They make it easy to perform operations on every item without writing complex for loops.


// Simple iteration example
const fruits = ["apple", "banana", "orange"];
fruits.forEach(fruit => console.log(fruit));
// Output: apple, banana, orange
                                    

forEach() Method

🔄

Basic forEach

Execute function for each element

const numbers = [1, 2, 3, 4];
numbers.forEach(num => {
    console.log(num * 2);
});
// Output: 2, 4, 6, 8
📍

With Index

Access element and its index

const colors = ["red", "green", "blue"];
colors.forEach((color, index) => {
    console.log(`${index}: ${color}`);
});
// Output: 0: red, 1: green, 2: blue

🔹 map() Method

Creates a new array by transforming each element:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

// Transform objects
const users = [{name: "John", age: 25}, {name: "Jane", age: 30}];
const names = users.map(user => user.name);
console.log(names); // ["John", "Jane"]

Output:

doubled: [2, 4, 6, 8]

names: ["John", "Jane"]

🔹 filter() Method

Creates a new array with elements that pass a test:

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

// Filter objects
const products = [
    {name: "Laptop", price: 1000},
    {name: "Phone", price: 500},
    {name: "Tablet", price: 300}
];
const expensive = products.filter(product => product.price > 400);
console.log(expensive); // [{name: "Laptop", price: 1000}, {name: "Phone", price: 500}]

Output:

evenNumbers: [2, 4, 6]

expensive: [Laptop: 1000, Phone: 500]

🔹 reduce() Method

Reduces array to a single value:

🔸 Sum Numbers

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

// Find maximum
const max = numbers.reduce((max, num) => num > max ? num : max);
console.log(max); // 5

🔸 Count Items

const fruits = ["apple", "banana", "apple", "orange", "banana"];
const count = fruits.reduce((acc, fruit) => {
    acc[fruit] = (acc[fruit] || 0) + 1;
    return acc;
}, {});
console.log(count); // {apple: 2, banana: 2, orange: 1}

Output:

sum: 15

max: 5

count: {apple: 2, banana: 2, orange: 1}

🔹 find() and findIndex() Methods

Find specific elements in arrays:

find() - Returns first matching element:

const users = [
    {id: 1, name: "John", age: 25},
    {id: 2, name: "Jane", age: 30},
    {id: 3, name: "Bob", age: 35}
];

const user = users.find(u => u.age > 28);
console.log(user); // {id: 2, name: "Jane", age: 30}

findIndex() - Returns index of first match:

const numbers = [10, 20, 30, 40];
const index = numbers.findIndex(num => num > 25);
console.log(index); // 2 (index of 30)

🔹 some() and every() Methods

Test array elements with conditions:

🔸 some() - Check if ANY element passes test

const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true

const ages = [16, 18, 20, 22];
const hasMinor = ages.some(age => age < 18);
console.log(hasMinor); // true

🔸 every() - Check if ALL elements pass test

const numbers = [2, 4, 6, 8];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true

const ages = [20, 22, 25, 30];
const allAdults = ages.every(age => age >= 18);
console.log(allAdults); // true

Output:

hasEven: true

hasMinor: true

allEven: true

allAdults: true

🔹 Chaining Methods

Combine multiple iteration methods:

const products = [
    {name: "Laptop", price: 1000, category: "electronics"},
    {name: "Shirt", price: 50, category: "clothing"},
    {name: "Phone", price: 800, category: "electronics"},
    {name: "Jeans", price: 80, category: "clothing"}
];

// Chain filter, map, and reduce
const totalElectronicsPrice = products
    .filter(product => product.category === "electronics")
    .map(product => product.price)
    .reduce((total, price) => total + price, 0);

console.log(totalElectronicsPrice); // 1800

Output:

totalElectronicsPrice: 1800

🧠 Test Your Knowledge

Which method creates a new array with transformed elements?