• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

135
Views
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 3 years ago · Juan Pablo Isaza
3 answers
Answer question

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 3 years ago · Juan Pablo Isaza Report

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 3 years ago · Juan Pablo Isaza Report

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 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error