Hello.
This is my first post here.
Task: Using the splice() method, keep only the items that sum up to 10 in the array.
Action:
- Sum of the array using Array.reduce((a,b) => a+b,0)
- For loop that iterates through the array while (i < Array.length)
- If sum > 10, call Array.splice(i,1)
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
for(let i=0; i<arr.length; i++) {
let sum = arr.reduce((a,b)=>a+b)
console.log(sum, ',', arr[i]);
if(sum > 10) { arr.splice(i,1) }
}
console.log(arr);
The answer I get is [4,1,5,1].
I don’t understand why that last item isn’t spliced as well.
Thank you in advance.