0

I have seen the solutions using push and slice but I wanted to achieve this using nested loops. When the number of elements in array are divisible by size, this code works but it doesn't work for other cases.

let arr2d = [];

function breakIt(arr, size){
  if(arr.length % size === 0){
    for (var i = 0; i < size; i++) { 
     arr2d[i] = new Array(size);
    } 

    console.log(arr2d);
    let increm = 0;

    for(let i = 0; i < (arr.length/size); i++){
      for(let j = 0; j < size; j++){
        arr2d[i][j] = arr[increm];
        increm++;
        //console.log(arr2d[i][j]);
        }
    }
   } else {
     console.log('Odd number of elements in arr');
   }

  console.log(arr2d);
}

breakIt(["a", "b", "c", "d"], 2);
breakIt(["a", "b", "c", "d", "e", "f"], 3);
breakIt([1, 2, 3, 4, 5, 6], 2);

//breakIt([0, 1, 2, 3, 4, 5], 4)should return [[0, 1, 2, 3], [4, 5]]
  • 2
    please add the wanted result and what not work. – Nina Scholz Sep 27 '19 at 12:10
  • breakIt(["a", "b", "c", "d"], 2); breakIt(["a", "b", "c", "d", "e", "f"], 3); breakIt([1, 2, 3, 4, 5, 6], 2); breakIt([0, 1, 2, 3, 4, 5], 4)should return [[0, 1, 2, 3], [4, 5]] The code gives me desired result when the function is called with first three but doesnt work with the last one. – user11417041 Sep 27 '19 at 12:14
  • please edit the question. – Nina Scholz Sep 27 '19 at 12:14

1 Answers1

0

You can achieve it with one loop as well:

Logic:

  • Loop over data.
  • Create 2 arrays,
    • result to have final output
    • temp to hold intermediate value
  • If number of elements are pushed in temp, you can clone and push cloned data in result. You will also have to do it after loop ends for any trailing values.

function breakIt(data, len) {
  const result = [];
  let temp = [];
  for (let i = 0; i < data.length; i++) {
    if (i % len === 0 && i > 0) {
      result.push(temp.slice());
      temp = [];
    }
    temp.push(data[i])
  }
  result.push(temp)
  console.log(result);
  return result;
}

breakIt(["a", "b", "c", "d"], 2);
breakIt(["a", "b", "c", "d", "e", "f"], 3);
breakIt([1, 2, 3, 4, 5, 6], 2);
breakIt([1, 2, 3, 4, 5, 6], 4);
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79