Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do values of an array count down multiple times with this code?

Please don’t downvote because of the title, I can’t explain this very good. When you use this code

const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var y = []


x.forEach(elt => {
    for(let i = 0; i < elt; i++){
        y.unshift(i)
    }
})

console.log(y)

it keeps counting down the array ‘x’ the length of x times.
Please explain this to me.
Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code is doing exactly what you’re asking it to do.

You are running a for-loop for every element in x.

So you are running

for (let i = 0; i < x[0]; i++) ... //i goes from 0 to 0
for (let i = 0; i < x[1]; i++) ... //i goes from 0 to 1
for (let i = 0; i < x[2]; i++) ... //i goes from 0 to 2
for (let i = 0; i < x[3]; i++) ... //i goes from 0 to 3
...

That’s why you’re getting those 9…0, 8…0, 7…0, and so on.

const x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let y = []


x.forEach(elt => {
    console.log(`For the element ${elt}`);
    //For each element in x, you are executing the following loop:
    for(let i = 0; i < elt; i++){
        console.log(`unshifting ${i}...`);
        y.unshift(i)
    }
    console.log(`End of each element (${elt}): ${y}`);
})

//if you want each element in x to unshift into y, you need to simply:

const z = [];

x.forEach(elem => z.unshift(elem))
console.log(z);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading