1

Hi guys Ive been sitting on this problem for hours now and although I think my code is right it still is not working. I need to get this answer:
var newArr = [["a", "b"], ["c", "d"]]
(arr and size will always be variables)

function separateIt(arr, size) {
 var newArr = [];
 for(var i = 0; i < arr.length; i += size){
  var sliceIt = arr.slice(arr[i],[arr[i]+size]);
  newArr.push(sliceIt);
 }
 return newArr;
}

console.log(separateIt(["a", "b", "c", "d"], 2));

Thanks for any help I am a beginner :)

swenm
  • 13
  • 1
  • 3

2 Answers2

1

You could use the indices and not the values of the array

var sliceIt = arr.slice(i, i + size);
//                      ^  ^^^^^^^^

function separateIt(arr, size) {
    var newArr = [];
    for (var i = 0; i < arr.length; i += size) {
        var sliceIt = arr.slice(i, i + size);
        newArr.push(sliceIt);
    }
    return newArr;
}

console.log(separateIt(["a", "b", "c", "d"], 2));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

The easiest approach I'd suggest is the following:

function separateIt(arr, size) {

  // creating a new Array to return
  // to the calling context:
  let res = [];
  while (arr.length) {

    // appending a new Array created from the
    // first element to the size-th element,
    // modifying the original array ('arr')
    // by removing those elements:
    res.push(arr.splice(0, size));
  }

  // returning the new Array:
  return res;
}
console.log(separateIt(["a", "b", "c", "d"], 2));
David Thomas
  • 249,100
  • 51
  • 377
  • 410