0

For example, If I have an array a=[1,2,3,4,5,6,7,8] and b=[]. On every click event, I am passing a number as a parameter. I need to push the array a[] to array b[] from the next element. For the first click, I am passing 3 as parameter. Now array b[] will be copied from a[0] to a[2] which gives me array b=[1,2,3].

When I click second time with passing 2 as parameter, Now array b[] will be copied from a[3] to a[4] which gives me array b=[1,2,3,4,5].

Desired result: click(3) = b[1,2,3] click(2) = b[1,2,3,4,5]

Instead I am getting this click(3) = b[1,2,3] click(2) = b[1,2]

a=[1,2,3,4,5,6,7,8];
b = [];

click(e){
for(let i=0; i<=e; i++){
b.push(a[i])
}

How to do this? Any thoughts!! Thanks in advance.

4
  • Can you give a more detailed explanation? Commented Aug 30, 2020 at 21:41
  • Consider revising your question. Confusing Commented Aug 30, 2020 at 21:41
  • I can't figure out what is the reason for adding a into the code Commented Aug 30, 2020 at 21:42
  • I revised my question. Hope you understand better now. Commented Aug 30, 2020 at 21:44

3 Answers 3

0

Whenever the click function gets called you loop from 0 to e. Instead you might want to loop from b.length (the next index to copy), e indices further (till b.length + e).

Sign up to request clarification or add additional context in comments.

Comments

0

The toString is only for formatting the code to show it here in the snippet better.

let a = [1,2,3,4,5,6,7];
let b = [];

function click(n) {
    for (let i=n; i>0; i--) {
        b = b.concat(a.splice(0,i));
        console.log(i + ': ' + '  a: ' + a.toString() + '    b: ' + b.toString());
    }
}

click(3);

Comments

0

I did as @JonasWilms suggested. This works.

let a = [1,2,3,4,5,6,7];
let b = [];

function click(n) {
    
    for (var i=b.length; i<= n; i++) {
       b.push(a[i]);
       
    }
    console.log(b);
}
click(1);
click(2);
click(3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.