I recently completed a JavaScript challenge asking to return a new array with all the values of the initial array doubled.
const numbers = [1, 2, 3];
function double() {
}
Except that I was to include some ES6 topics of de-structuring and rest/spread operators as well as recursion. Well, I completed as best as I could to come to a solution. This was my solution:
const numbers = [1, 2, 3];
function double(arr){
const doubledNumbers = [];
for (var i = 0; i < arr.length; i ++){
const dubba = arr[i];
const bubba = dubba * 2;
doubledNumbers.push(bubba);
}
return doubledNumbers;
}
The other requirement was to not use any array helper method (map, reduce etc), so I did not use map()
, but instead a for
loop. However, I could not wrap my head around implementing de-structuring or rest/spread operators, concepts I thought I knew pretty well, never-mind recursion.
Here's one possible implementation - destructure the parameter of double
, taking out the first number in the array, and use rest syntax to put the rest of the numbers into another array. Then, double
the rest of the array, and spread it into a new (returned) array, headed by the first number times 2:
const numbers = [1, 2, 3];
function double([firstNum, ...rest]) {
const restDoubled = rest.length ? double(rest) : [];
return [firstNum * 2, ...restDoubled];
}
console.log(double(numbers));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With