DEV Community

jolamemushaj
jolamemushaj

Posted on

4 1

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
huykonofficial profile image
Huy Kon

another way
Array.from(array, x => x *2)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay