Click here to Skip to main content
14,173,165 members
Rate this:
 
Please Sign up or sign in to vote.
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:

<body>

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

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

</body>

    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 = "";

     }
Posted
Updated 15-May-19 13:18pm

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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[^]
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web05 | 2.8.190524.3 | Last Updated 15 May 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100