Sat May 06 2023

Array Iteration in JavaScript: A Comprehensive Guide Part 1

JavaScript127 views

Arrays is one of the most commonly used data structures and JavaScript provides a powerful set of tools for working with Arrays. It allows you to store multiple values in a single variable, and JavaScript includes several methods to iterate over these values effectively. In this part, we'll explore the various ways to iterate over arrays in JavaScript, including traditional loops and modern array methods. Let's talk about each method and when to use them.

1. forEach Method

The forEach method is a built-in array method that allows you to execute a provided function once for each array element. It’s widely used because of its simplicity and clean syntax.

When to Use:

You can use forEach to apply a function to each element in the array. However, note that forEach does not return a new array or allow you to use break and continue statements.

num.forEach((value, index) => {
document.getElementById('forEData').innerHTML += index + ' - ' + value +'<br />';
})

2. map Method

The map method is an ES6 array method that iterates over each array element and applies a function to each element. Unlike forEach, map creates a new array with the modified values. Its return value is added as a single element in the new array.

When to Use:

map can be used to transform each element in the array and create a new array with the results.

num.map((value, index) => {
document.getElementById('mapData').innerHTML += index + ' - ' + value +'<br />';
})

3. flatmap Method

The flatMap method combines the functionality of map and flat. It first maps each element using a mapping function, then flattens the result into a new array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. This is particularly useful when working with arrays of arrays, as it allows you to flatten nested arrays by one level automatically.

When to Use:

You can use flatMap when you need to both transform each element in the array and flatten the result by one level. It’s ideal for operations that generate arrays of arrays, like splitting strings or expanding elements.

const newArray = num.flatMap((value) => value + 2);
document.getElementById('flatMapData').innerHTML = newArray;

4. filter Method

The filter method creates a new array with elements that pass a specified test function. This is particularly useful when you want to filter out certain elements based on a condition. It should return a truthy value to keep the element in the resulting array, and a falsy value otherwise.

When to Use:

You can use filter when you want to create a new array containing only elements that meet certain conditions.

const newArray = num.filter((value) => value > 40);
document.getElementById('filterData').innerHTML = newArray;

Conclusion

JavaScript offers a wide variety of methods to iterate over arrays, each with its specific use case. By understanding these methods and their optimal usage scenarios, you can write more efficient and readable code. Whether you need to transform, filter, or aggregate data, JavaScript’s array iteration methods provide all the tools necessary to handle your tasks.

Array Iteration in JavaScript: A Comprehensive Guide Part 1

File Name: js-array-iteration.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Iteration in JavaScript</title>
    <style>
        section {
            display: flex;
            gap: 10;
            justify-content: space-between;
        }

        section div.col {
            width: calc(100% / 4);
        }

        section div.col > div {
            margin: 10px 0;
        }

        button { margin-bottom: 10px; }
    </style>
    <script>
        let num = [25, 45, 81, 64, 10, 46, 89, 49, 22, 40, 78, 62];

        const getForEach = () => {
            num.forEach((value, index) => {
                document.getElementById('forEData').innerHTML += index + ' - ' + value +'<br />';
            })
        }

        const getMap = () => {
            num.map((value, index) => {
                document.getElementById('mapData').innerHTML += index + ' - ' + value +'<br />';
            })
        }

        const getFlatMap = () => {
            const newArray = num.flatMap((value) => value + 2);
            document.getElementById('flatMapData').innerHTML = newArray;
        }

        const getFilter = () => {
            const newArray = num.filter((value) => value > 40);
            document.getElementById('filterData').innerHTML = newArray;
        }
    </script>
</head>
<body>
    <section>
        <div class="col">
            <button type="button" onclick="getForEach()">ForEach Iteration</button>
            <div id="forEData"></div>
        </div>
        <div class="col">
            <button type="button" onclick="getMap()">Map Iteration</button>
            <div id="mapData"></div>
        </div>
        <div class="col">
            <button type="button" onclick="getFlatMap()">Flat Map Iteration</button>
            <div id="flatMapData"></div>
        </div>
        <div class="col">
            <button type="button" onclick="getFilter()">Filter Iteration</button>
            <div id="filterData"></div>
        </div>
    </section>
</body>
</html>

Result Screenshot(s)

Array Iteration in JavaScript: A Comprehensive Guide Part 1Working Sample0

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.