-1

How would I be able to iterate through an array and display 3 values in sequential order at a time through a click event?

Example:

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];

Looking for result of: 1,2,3 and then click for 4,5,6 then 7,8,9.

A.Rashad
  • 1,066
  • 12
  • 26
Carmen
  • 125
  • 1
  • 3
  • 9

4 Answers4

4

Simply increase your loop variable by 3 instead of 1:

for (var i = 0; i < array.length; i += 3) {
    console.log(array[i], array[i+1], array[i+2]);
    // or console.log(array.slice(i, 3));
}

You could also Split array into chunks in advance.


Edit: Apparently you don't want to iterate (as you say in the title). The same applies to successive clicks though. Keep a counter i around and increase it by 3 on each click.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Feel free to use a counter and show the next three values.

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var counter = 0;
document.getElementsByTagName('button')[0].addEventListener('click', function() {
  document.body.append(array[counter++] + array[counter++] + array[counter++]);
});
<button>click</button>
<span></span>
Namaskar
  • 2,114
  • 1
  • 15
  • 29
0

Here's another solution, if you don't mind mutating your original array.

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];

function clickMeForThree(arr) {
    for (let i=0; i < 3; i++) {
        console.log(arr[i])
        array.shift()
    }
}

clickMeForThree(array)
clickMeForThree(array)
clickMeForThree(array)
Christopher Messer
  • 2,040
  • 9
  • 13
0

You can have a function that returns current value and increments the index counter. Then call it thrice to get next three values.

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var curr = 0;
function nextVal(){
    if(curr<array.length)
        return array[curr++];
    else
        return '';
}

function printNextThree(){
    console.log(nextVal()+','+nextVal()+','+nextVal());
}

Now simply call printNextThree() function on your click event for the desired result.

Nitesh
  • 96
  • 8