'Why is my code returning " [ undefined, undefined, undefined ]"?
function sumAll(arr) {
arr.sort();
let lum = [];
for (let i = arr[1]; i > arr[0]; i--) {
lum.push(arr[i]);
}
return lum;
}
console.log(sumAll([1, 4]));
I want my code to do 4-3, then add the result to lum and so on until it reaches 1 but i'm stuck at this point. I don't know why it returns undefined.
Solution 1:[1]
You're pushing arr[i] onto the result:
lum.push(arr[i]);
So for example when i is 4 (because arr[1] is 4), what is the value arr[4] that you're pushing to the result? It's undefined in the array provided. I suspect you meant to just push i to the result?:
lum.push(i);
For example:
function sumAll(arr) {
arr.sort();
let lum = [];
for (let i = arr[1]; i > arr[0]; i--) {
lum.push(i);
}
return lum;
}
console.log(sumAll([1, 4]));
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 | David |
