Map Array Values Without Using Map Method in JavaScript



Mapping array values without using the map method can be done by using forEach() method, reduce() method, for loop, and while loop. In this article, we will implement some methods that will work efficiently for mapping array values.

Table of Content

Mapping array values without using map method can be done in the following ways:

Using forEach()

The forEach() method allows you to iterate through each element in an array and apply a transformation to it. As you do this, you manually add the transformed values to a new result array.

Example

The following is a simple example of using forEach() method for mapping array value:

function mapUsingForEach(arr, transform) {
    let result = [];
    arr.forEach(item => result.push(transform(item)));
    return result;
}

const numbers = [1, 2, 3, 4];
console.log(mapUsingForEach(numbers, num => num * 2));

Output

[ 2, 4, 6, 8 ]

Using reduce()

The reduce() method allows you to combine values while applying transformations. It iterate through the array, applies the transformation, and adds the results to an accumulator array.

Example

The following is a simple example of using reduce() method for mapping array value:

function mapUsingReduce(arr, transform) {
    return arr.reduce((acc, item) => {
        acc.push(transform(item));
        return acc;
    }, []);
}

const numbers = [3, 4, 5, 6];
console.log(mapUsingReduce(numbers, num => num * 3));

Output

[ 9, 12, 15, 18 ]

Using a for Loop

A traditional for loop can be used to manually transform elements by iterate through each index of the array. The transformed values are then stored in a result array.

Example

The following is a simple example of using for loop for mapping array value:

function mapUsingForLoop(arr, transform) {
    let result = [];
    for (let i = 0; i < arr.length; i++) {
        result.push(transform(arr[i]));
    }
    return result;
}

const numbers = [1, 3, 5, 7];
console.log(mapUsingForLoop(numbers, num => num * 2)); 

Output

[ 2, 6, 10, 14 ]

Using while Loop

The while loop continues until it reaches the end of the array, applying transformations and storing the results in a new array.

Example

The following is a simple example of using while loop for mapping array value:

function mapUsingWhileLoop(arr, transform) {
    let result = [];
    let i = 0;
    while (i < arr.length) {
        result.push(transform(arr[i]));
        i++;
    }
    return result;
}
const numbers = [1, 3, 5, 7];
console.log(mapUsingWhileLoop(numbers, num => num * 3)); 

Output

[ 3, 9, 15, 21 ]

Conclusion

In this article, we have four methods to map array values without using the map method in JavaScript. All four methods are simple to use and efficient. You can use any of the above methods.

Updated on: 2025-02-25T14:51:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements