Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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

Ideally, I would like to click a button ("Next Set" in the CodePen example) and load the next set (of 2) thumbnail images. This is in an effort to not load all of the images at once, which could be hundreds.

Problem: I cannot figure out how to dynamically slice the array on click (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 continuously added to the gallery. Furthermore, I would have to have too many sets of the above to keep slicing 5 out at a time.

I have tried:

  • Splitting the array into smaller arrays
  • for loops and $.each loops

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

Here is my CodePen

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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

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

Replace your existing click() with this (including the declaration of lastIndex) to try it:

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've moved the slice() line outside the for loop. There's no need to slice a new array for every iteration.

Here's a CodePen using .slice().

An alternate method is to use to shift() to peel off the first item in the array with each iteration:

var nextItem = myArray.shift()

This is destructive though (it removes the item 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 your 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().

about 4 years ago · Santiago Trujillo Denunciar

0

your problem is simple i think. you do a slice and allways get back 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);
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda