Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to map array values without using map method in JavaScript ?

How to map array values without using map method in JavaScript ?

Array elements can be mapped by using looping methods in JavaScript. The map() method creates a new array with the results of the output of a function called for each array element. This can also be implemented using for loop in JavaScript.

Approach: For this, we can create two arrays, in which one array contains the array elements that are to be mapped, and the second array stores all the return values of the corresponding function.  We can use the JavaScript Array push() method to push the return values of the function in the output array.

Syntax:

array.push(element1, element2, element, ... , elementN )

The Array length method can be used to find the length of the corresponding array.

Syntax:

array.length

Return value: Number

Example:

Javascript




const arr = [4, 5, 10, 3, 8, 6];
let result = [];
 
// Square function returns square of a number
const square = function (num) {
    return num * num;
}
 
for (let i = 0; i < arr.length; i++) {
    result.push(square(arr[i]));
}
 
// Expected output: [16 ,25, 100, 9, 64, 36]
console.log(result);


Output

[ 16, 25, 100, 9, 64, 36 ]

The indices of the elements in the output array are shown before the numbers in the output as well as the length of the output array.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments