Remove Items Using Splice and Array.Reduce

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:

  1. Sum of the array using Array.reduce((a,b) => a+b,0)
  2. For loop that iterates through the array while (i < Array.length)
  3. 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.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Splice changes the length of your array, which means that you can get unexpected results as you iterate over your array, to include skipping entries.

I would recommend never using a loop like this to modify the length of your array. I’d use a high order method or copy into a second, modified array.

1 Like

Thank you JeremyLT.
I shall adhere to these guidelines when posting from here on.

Ah! Of course.
I knew it was something small, but important.
Thanks again.

1 Like

you are changing the array being iterated over

let’s make an example of what happens:

0 1 2 3 4 5 // indexes
4 5 1 9 8 1 // numbers at those indexes 

first i is equal to 0, the check fail, and the item at index 0 is removed:

0 1 2 3 4
5 1 9 8 1

now it's time for index 1, and arr[i] is now 1

notice what happen? the 5 is impossible to remove, as it’s being jumped over

EDIT: I came late to the party :sweat:

1 Like

It’s all good, @ieahleen.
Rather than just use: arr.splice(1,4), I’m determined to figure out the pseudocode and iterate through the array, to further my understanding. So, don’t tell me yet. I’ll post it here when I do :slight_smile:

Why are you using a .reduce() in your for loop?

1 Like