user2557504 user2557504 - 5 months ago 32
jQuery Question

Display first 4 of an array then next four on next

I am trying to figure out a way to show only the first four elements in an array dynamically like some how filter it. There are 8 items. Is there a way to filter on the first 4. then when they click next, it displays the next four?



$("#test").click(function(){

fruits.splice(0, fruits.length, "Lemon", "Kiwi");
document.getElementById("demo").innerHTML = fruits;

});
$("#next").click(function(){

fruits.next++;

});

function next(number)
{
var index = fruits.indexOf(number);
index++;
if(index >= fruits.length)
index = 0;

return fruits[index];
}
var fruits = ["Banana", "Orange", "peaches", "bananas","papaya","watermelon","strawberry","cheese"];

var col1 = ["Banana", "Orange","pies","pretzels"];
var col2 = ["Banana", "Orange"];
document.getElementById("demo").innerHTML = fruits;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Click the button to add and remove elements.</p>


<button id="next" onclick="next();">next</button>
<p id="demo"></p>




Answer

You can use slice() to selecting elements from array.

var fruits = ["Banana", "Orange", "peaches", "bananas","papaya","watermelon","strawberry","cheese"];

$("p").text(fruits.slice(0, 4));
$("button").click(function(){
    $("p").text(fruits.slice(4, 8));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
<button>Next</button>