Click here to Skip to main content
15,797,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<pre>I have an array of 20 elements. I want to display first five elements on click of a button, then next five elements on another click, and so on. I would be grateful if you could help me with the code.
I know my approach is wrong, but what I have tried displays the result two times correctly but not the third time.

What I have tried:


<button onclick="nextElems();"> Try </button>

<div id="yes"> </div>


    var words = ["day", "white", "go", "low", "wise", "up", "sit", "now", 
    "good", "grapes", "banana",
    "mango", "orange", "pears", "melon", "guava", "sunflower", "marigold", 
    "jasmine", "sunflower"];

    var x = "";

    var count = 0;

    function nextElems() {

        if (count < words.length) {

            var newArray = words.slice(0, 5);

            x += '<div>' + newArray + '</div>';

            document.getElementById('yes').innerHTML = x;

            count = newArray;

        } else {

            count = 0;

            var secondArray = words.slice(5, 10);

            x += '<div>' + secondArray + '</div>';

            document.getElementById('yes').innerHTML = x;


        x = "";

Updated 15-May-19 14:18pm

1 solution

Use a Queue or a Stack, depends on what order you want to return them.

You can then "dequeue" or "pop" 5 at a time, without having to keep track.

data structures - How do you implement a Stack and a Queue in JavaScript? - Stack Overflow[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900