I have an Array of numbers: var arr = [1,2,3,4,5]
I want to get a list like this: input_1 = 1, input_2 = input_1 * 2, input_3= input_2 * 4 ..
With me can i do in javascript?
Asked
Active
Viewed 515 times
-1

fedemap
- 1
- 1
-
2Are you asking for ["variable" variables](https://stackoverflow.com/questions/5187530/variable-variables-in-javascript) or just how to convert this array into another? – VLAZ Jun 15 '21 at 17:13
-
If you want a variable for every element in your array dynamically, that's not possible without `eval` or similar. – MinusFour Jun 15 '21 at 17:36
-
You can do simple for loop with Object.defineProperty like in below psudo code. function creareVariables (array){ let parent =this;array.forEach((el,idx)=>{if(!idx){Object.defineProperty(parent,'input_'+idx, {value:el})} else{ Object.defineProperty(parent, 'input_'+idx,{value:parent['input_'+(idx-1)]*el})}})} warning untested code.. sent from mobile – Karthikeyan Jun 15 '21 at 18:21
-
Do you have an initial approach that you have tried? – Rex Charles Jun 15 '21 at 20:01
3 Answers
0
Try
var output = {};
arr.forEach((item, i) => {
output[i+1] = i === 0 ? 1 : (output[i] * (i * 2));
});
Output
{1: 1, 2: 2, 3: 8, 4: 48, 5: 384}

Vishnudev Krishnadas
- 10,679
- 2
- 23
- 55
0
You just need to keep track of the last calculated value and multiply it by the current element. There are lots of different ways to do that, here is one:
var arr = [1,2,3,4,5];
let last = 1;
const output = arr.map(el => last *= el);
console.log(output);

James
- 20,957
- 5
- 26
- 41
0
Here is a more functional-like implementation using the reduce
method (Doc).
var arr = [1,2,3,4,5];
const result = arr.reduce(
(resultArr, _, i) => {
if (i === 0) {
// base case:
return [1];
} else {
// step case:
return [
...resultArr,
resultArr[resultArr.length - 1] * (2 ** i),
];
}
},
[],
);
console.log(result);

Alvin Leung
- 668
- 1
- 5
- 10