I'm trying to write a quite simple program that divides an array in another array of defined size smaller arrays, however the push()
method is not working. Could someone please help me with it?
function chunk(array, size) {
var newArray = [];
var tempArray = [];
for (let i = 0; i < array.length / size; i++) {
for (let j = size * i, k = 0; j < size * i + size; j++, k++)
tempArray[k] = array[j];
newArray.push(tempArray);
}
return newArray;
}
var data = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(chunk(data, 2));
The ideal output should be [[1, 2],[3, 4], [5, 6], [7, 8]]
.
However im getting [[7,8],[7,8],[7,8],[7,8]]
.
var tempArray = [];
inside of your first for loop. Currently, you're pushing the same array reference each time, and so modifications to it will impact it within your array – Selwintemparray
in he very beginning and then overwriting its elements and pushing the same array multiple times – Lezlielg