Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda