How can you slice an array dynamically in Javascript / jQuery?

I have a photo gallery that includes images that will be constantly uploading. The PHP array has been converted / encoded to a JSON array so that I can manipulate the data using JavaScript.

Ideally, I would like to click the button ("Next Set" in the CodePen example) and load the next set (of 2) thumbnails. This is done in order not to download all the images at once, which can be hundreds.

Problem: I can't figure out how to dynamically slice the array on push (next 5 images). I can, of course, load, say, 2 at a time:

myArray.slice(0,2);
myArray.slice(3,5);

      

However, this will not work because images will be constantly added to the gallery. Also, I would have to have too many of the above to cut 5 pieces at a time.

I tried:

  • Dividing an array into smaller arrays
  • for

    and $.each

    hinges

I essentially need to be able to move the start and end index of the slice (for example) 2 on click. Right now, it just slices the same two images because slicing is not dynamic.

Here is my CodePen

+3


source to share


2 answers


I don't think there is a way to do exactly what you want, but you can just keep track of where you were in the array and segment from there, like this:

var nextSet = myArray.slice(lastIndex, lastIndex + 2);

      

Replace the existing one click()

with this (including the declaration lastIndex

) to try:

var lastIndex = 0
$('.button').click(function() {
  var nextSet = myArray.slice(lastIndex, lastIndex + 2);
  lastIndex += 2;
  for (var i = 0; i < 2; i++) {
    var li = $('<li/>').attr('role', 'menuitem').appendTo('.myList').append('<img src=' + nextSet[i] + '>');
  }
});

      

Note that I was moving the line slice()

outside the loop for

. There is no need to slice a new array for each iteration.

Here's a CodePen using.slice()

.



An alternative method is to use shift()

to remove the first element in the array with each iteration:

var nextItem = myArray.shift()

      

It's destructive though (it removes an element from the original array), so you'll need to make a copy of the original array first if you want to use it for anything else. Replace click()

with:

$('.button').click(function() {
  for (var i = 0; i < 2; i++) {
    var nextItem = myArray.shift();
    var li = $('<li/>').attr('role', 'menuitem').appendTo('.myList').append('<img src=' + nextItem + '>');
  }
});

      

Here's a CodePen using.shift()

.

+2


source


Your problem is simple I guess. you do a slice and always return the same array



var array = [0,1,2,3,4,5];
let newArray1 = array.slice(0,2); // returns a new array
let newArray2 = array.slice(0,2); // returns the same new array

for(var i = 0; i < 2; i = i+2) {
  result = array.slice(i, i+2);
  console.log(result);
}

      

0


source







All Articles