Three ways to iterate an array

jolamemushaj

jolamemushaj

Posted on September 16, 2022

Three ways to iterate an array

Given an array of integers, return a new array with each value doubled.

For example: [2, 4, 6] --> [4, 8, 12]

Number #1: We use a for loop to iterate over the elements, transform each individual one, and push the results into a new array.

function doubleValues(array) {
    let result = [];
    for (let i = 0; i < array.length; i++) {
        result.push(array[i] * 2);
    }
    return result;
}

console.log(doubleValues([1, 2, 3, 4]));
// [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Number #2: For-of loop.

function doubleValues(array) {
    let result = [];
    for (const element of array) {
        result.push(element * 2);
    }
    return result;
}

console.log(doubleValues([1, 2, 3, 4]));
// [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Number #3: JavaScript Array type provides the map() method that allows you to transform the array elements in a cleaner way.

const array = [1, 2, 3, 4];
const doubleValues = array.map(element => element * 2);
console.log(doubleValues);
// [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
jolamemushaj
jolamemushaj

Posted on September 16, 2022

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

Sign up to receive the latest update from our blog.

Related

Three ways to iterate an array
javascript Three ways to iterate an array

September 16, 2022

React Components #day32
100daysofcode React Components #day32

November 2, 2021

TO Do List {Day -25}
100daysofcode TO Do List {Day -25}

September 8, 2021

#100daysOfCode [Day - 05]
github #100daysOfCode [Day - 05]

August 15, 2021