I want someone to review my code and tell me what I did wrong. I want a function that receives an array of numbers as a parameter and returns a new array with each element multiplied by two.
function duplicate(arr) {
let numDouble = arr;
for (let i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
Total = numDouble * 2;
}
}
return numDouble;
}
const arr = [1,2,3,4,5]
console.log(duplicate(arr))
Your solution was not working because you weren't assigning the new value into the array
It will works if you use the following code to do this :
numDouble[i] = numDouble[i] * 2;
By the way, there is no need to check if the value is 0 because 0 * 2 still equal 0 which works perfectly. so you could have removed the if(arr[i]!=0) part.
Also, when you're doing let numDouble = arr; you aren't creating a new array but assigning the existing array reference into the variable.
If you want to create a new array you can use the spread operator which is used for example to duplicates array.
Example : let numDouble = [...arr];
You would have checked if there was a division that might cause a problem
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)
Another solution that might works better is the map function which take a function an apply it to every item of the array
So for example you could do this :
const arr = [1, 2, 3, 4]
const multiplyByTwo = function(number) {
return number * 2
}
console.log(arr.map(multiplyByTwo))
Or even with one line of code using arrow functions :
const arr = [1,2,3,4]
console.log(arr.map(x => x*2))
There are a couple of errors in your code, outlined below:
let numDouble = arr;
This does not create a new array. Instead it creates a new reference to the same array. This means that when you modify numDouble you're also modifying arr
if(arr[i]!=0)
I am not sure what your trying to do with this condition, but it is unnecessary as 2* 0 = 0 anyway. Unless you want to exclude 0 value from the final array ?
Total = numDouble * 2;
The variable Total is not defined. Also in javascript the convention is to use camelCase for variable names.
Furthermore numDouble is an array here, you can't use the multiplication operator. numDouble * 2 evaluates to NaN
Possible implementation
A possible implementation for your function would be:
function duplicate(arr) {
const doubleNum = []
for (let i = 0; i < arr.length; i++) {
doubleNum.push(2 * arr[i])
}
return doubleNum
}
const arr = [1,2,3,4]
console.log(duplicate(arr))
Although in real life, we would simply use map like so :
const numDouble = arr.map(i => 2*i)
var a=[2,1,5];
function duplicate(arr){
var Total=[];
for(let i = 0; i < arr.length; i++){
if(arr[i]!=0){
Total.push(arr[i] * 2);
}
}
console.log(Total)
return Total;
}
duplicate(a);
you can use the push() method . it adds one or more elements to the end of an array