Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base Algorithm Scripting by chopping the array with splice function in Javascript

Now I am working on a exercise in freecodecamp. Currently I got an logical error but do not why the failure happens.

In the code,I have to build in a function, which chop the input array based on the parameter. The testing result should be as follows:

chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]].

And my code are as follows:

function chunkArrayInGroups(arr, size) {
  var array = [];
  for (var x = 0; x < arr.length ; x+=size){
    var spliceArr = arr.splice(0,size);
    array.push(spliceArr);
  }
  array.push(arr);
  return array;
}

chunkArrayInGroups(["a", "b", "c", "d","e"], 2);

For most of the conditions, the code works. But for the last condition i.e

chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]].

in this case I cannot get the correct answer. I tested in console log, and turn out the output is like

[[0, 1], [2, 3], [4, 5], [6, 7, 8]].

I know that it is not a difficult question and there are lots of better way to approach it, but can I know what is the logic fallancy in this code? Many thanks!

like image 303
Pak Hang Leung Avatar asked Sep 12 '26 08:09

Pak Hang Leung


1 Answers

Instead of splice use slice. This will also guarantees that the original array is not modified.

Like this (working demo):

function chunkArrayInGroups(arr, size) {
  var array = [];
  for (var x = 0; x < arr.length; x += size) {
     // take elements from current index (`x`) to `x` + `size`
     // (do not remove them from the original array, so the original size is not modified either)
    var sliceArr = arr.slice(x, x + size);
    array.push(sliceArr);
  }
  return array;
}


console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2)); //should return [["a", "b"], ["c", "d"]].
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)); // should return [[0, 1, 2], [3, 4, 5]].
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)); // should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)); // should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]]
like image 83
lealceldeiro Avatar answered Sep 13 '26 22:09

lealceldeiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!