'Referencing one array to make changes in another given certain conditions in JavaScript [closed]
I have an array, called arr1
, example [9, 0, 0 ,9, 9]
. I made a copy of this and called it arr2
. I am trying to add the value one (1
) to certain indexes in arr2
, dependent on the index position of arr1
and it being a nine (9
).
For example,
if arr1[0] == 9, add one (1) to indexes [0], [3], [4] in arr2
if arr1[3] == 9, add one (1) to indexes [0], [2], [3] in arr2
if arr1[4] == 9, add one (1) to indexes [0], [1], [4] in arr2
So arr2
becomes [12, 1, 1, 11, 11]
.
Hope this makes sense, bear with me, I'm new to this.
Cheers.
Solution 1:[1]
The following code is what achieves your task.
var arr1 = [9, 0, 0 ,9, 9];
var arr2 = [...arr1]; // create a copy or a clone or array one
if(arr1[0] == 9){
arr2[0] += 1;
arr2[3] += 1;
arr2[4] += 1;
}
if(arr1[3] == 9){
arr2[0] += 1;
arr2[2] += 1;
arr2[3] += 1;
}
if(arr1[4] == 9){
arr2[0] += 1;
arr2[1] += 1;
arr2[4] += 1;
}
console.log(arr2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Albert Alberto |