Troubleshooting
The reason your solution did not work is because you forgot to assign the new value back into the array.
To make it work, you can simply update the code as follows:
numDouble[i] = numDouble[i] * 2;
It's unnecessary to check if the value is 0
since multiplying by 0 always results in 0. Therefore, you could have omitted the if(arr[i]!=0)
condition.
Additionally, when you write let numDouble = arr;
, you are not creating a new array but merely referencing the existing one.
If you wish to create a new array, consider using the spread operator for duplicating arrays.
For instance: let numDouble = [...arr];
You should also watch out for any potential division-related issues that could arise.
Here's an example:
function duplicate(arr) {
let numDouble = [...arr];
for (let i = 0; i < arr.length; i++) {
numDouble[i] = numDouble[i] * 2;
}
return numDouble;
}
const arr = [1, 2, 3, 4]
const newArr = duplicate(arr)
console.log(newArr)
Alternative Approach
Another more efficient solution involves utilizing the map
function, which applies a specified function to each element of an array.
You can achieve this by:
const arr = [1, 2, 3, 4]
const multiplyByTwo = function(number) {
return number * 2
}
console.log(arr.map(multiplyByTwo))
Alternatively, you can condense the code further using arrow functions in just a single line:
const arr = [1,2,3,4]
console.log(arr.map(x => x*2))