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

152
Vistas
JavaScript Splitting array into two dimensional array

Problem: Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

Why does my test2 variable not working?

function chunkArrayInGroups(arr, size) {
  let resArr = [];
  for (let i = 0; i < arr.length; i++) {
    resArr.push(arr.splice(0, size));
  }
  return resArr;
}
let test = chunkArrayInGroups(["a", "b", "c", "d"], 2);
console.log(test);
// returns correct [["a", "b"], ["c", "d"]]

let test2 = chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);
console.log(test2);
// should return [[0, 1], [2, 3], [4, 5]] 
//but returns [[0, 1], [2, 3]]

Why?

Thank you!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

arr.length changing on every iteration. And with incrementing i does not full fill condition.

Try below snippet

function chunkArrayInGroups(arr, size) {
  let resArr = [];

  while (arr.length) {
    resArr.push(arr.splice(0, size));
  }

  return resArr;
}

let test = chunkArrayInGroups(["a", "b", "c", "d"], 2);
console.log(test);

let test2 = chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2);
console.log(test2);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Since we're using splice, we're modifying the length of the original array, which means we shouldn't rely on it to loop through. Instead, we should loop through a range equalling to the length of the array we want to return, which can be calculated by just dividing inputArr.length / size.

You can create a "range" and loop through it with a for..of loop by using Array(number).keys()

const caseOne = ['a', 'b', 'c', 'd'];
const caseTwo = [0, 1, 2, 3, 4, 5];
const caseThree = [1, 'hi', 3, 9, 'a', { hello: 'world' }, 7563, 'c', 3, [1, 2, 3]];

const chunkArray = (arr, num) => {
    // The final array we'll push to
    const final = [];

    // Loop through the future length of the "final" array
    for (const _ of Array(Math.ceil(arr.length / num)).keys()) {
        final.push(arr.splice(0, num));
    }

    return final;
};

console.log(chunkArray(caseOne, 2));
console.log(chunkArray(caseTwo, 2));
console.log(chunkArray(caseThree, 3));

You could also use the reduce method:

const caseOne = ['a', 'b', 'c', 'd'];
const caseTwo = [0, 1, 2, 3, 4, 5];
const caseThree = [1, 'hi', 3, 9, 'a', { hello: 'world' }, 7563, 'c', 3, [1, 2, 3]];

const chunkArray = (arr, num) => {
    return [...Array(Math.ceil(arr.length / num)).keys()].reduce((acc) => {
        acc.push(arr.splice(0, num));
        return acc;
    }, []);
};

console.log(chunkArray(caseOne, 2));
console.log(chunkArray(caseTwo, 2));
console.log(chunkArray(caseThree, 3));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're using an index i which moves forward by one element, but meanwhile you're removing two per cycle, so the index falls beyond the array length sooner than you expect.

Instead of using an indexed for, just use a while condition that checks whether your array is empty or not. If it's not empty, countinue splice-ing:

function chunkArrayInGroups(arr, size) {


  let resArr = [];
  
  while (arr.length > 0) {
    resArr.push(arr.splice(0, size));
  }

  return resArr;
}

let test = chunkArrayInGroups(["a", "b", "c", "d"], 2); 
console.log(test);

let test2 = chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2); 
console.log(test2);
about 4 years ago · Juan Pablo Isaza 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