Kilax31
Kilax31

Reputation: 35

Possible bug/misunderstanding of splice and slice

I have the next loop:

    rolling_average_delta_follower=[];
    followers=[32,34,36,38,40,42,44,46,48,50,52,54,56] // .length = 12
    delta_followers=[50,52,54,56,58,60,62,64,66,68,70,72,74]  // leng= 12

     for (i = 0; i < followers.length ; i++) {

                copie = delta_followers.slice(0); //creates duplicate of array delta_followers so I keep source original and not cut from it
                copie.splice(7,i) // supposed to create an array that contains numbers from 50 to 64 -> next time the for executes it should go 52 to 66 and so on
                console.log(copie)
                for (i = 0; i < 8; i++) {  // the 7 numbers added previously in the one array are getting summed up
                    totalx += copie[i]
                }
                rolling_average_delta_follower.push(totalx) // the sum of each array previously created is getting added to the main array where I need the data.


        }

All good until I try to actually execute it, I end up with with a forever loop that I seem not to be able to escape.

Any help would be appreciated.

Thank you!

Upvotes: 1

Views: 48

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

To make a copy of an array use the spread operator.

const copy = [...original];

To sum the values of an array use reduce.

const sum = array.reduce((sum, item) => sum + item, 0);

Upvotes: 1

Bsalex
Bsalex

Reputation: 2970

The problem is here:

for (i = 0; i < 8; i++) {  // the 7 numbers added previously in the one array are getting summed up
    totalx += copie[i]
}

By this code you override i used in the loop above. Just use another variable name here. (j ?)

Upvotes: 1

Related Questions