Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the nth power of array element present at nth index using JavaScript
We need to write a JavaScript function that takes an array of numbers and maps each element to its power based on its 0-based index position. For example, the element at index 0 is raised to power 0, the element at index 1 is raised to power 1, and so on.
Problem Statement
Create a function that transforms an input array where each element is raised to the power of its index position, then return the resulting array.
Example
Here's how to implement this using a traditional for loop:
const arr = [5, 2, 3, 7, 6, 2];
const findNthPower = (arr = []) => {
const res = [];
for(let i = 0; i
[ 1, 2, 9, 343, 1296, 32 ]
How It Works
The transformation follows this pattern:
- Index 0: 50 = 1
- Index 1: 21 = 2
- Index 2: 32 = 9
- Index 3: 73 = 343
- Index 4: 64 = 1296
- Index 5: 25 = 32
Using Array.map() Method
A more functional approach using the map() method:
const arr = [5, 2, 3, 7, 6, 2];
const findNthPowerMap = (arr = []) => {
return arr.map((element, index) => Math.pow(element, index));
};
console.log(findNthPowerMap(arr));
[ 1, 2, 9, 343, 1296, 32 ]
Using Exponentiation Operator
Modern JavaScript allows using the ** operator instead of Math.pow():
const arr = [5, 2, 3, 7, 6, 2];
const findNthPowerModern = (arr = []) => {
return arr.map((element, index) => element ** index);
};
console.log(findNthPowerModern(arr));
[ 1, 2, 9, 343, 1296, 32 ]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| For Loop | Good | Fastest | All browsers |
| Array.map() | Excellent | Good | ES5+ |
| Exponentiation (**) | Excellent | Good | ES2016+ |
Conclusion
All three approaches solve the problem effectively. Use Array.map() with the ** operator for modern, readable code, or stick with the for loop for maximum compatibility and performance.
