gowtham gowtham - 7 months ago 19
Javascript Question

Getting Error: TypeError: Cannot set property '0' of undefined

Here I'm trying to create new array based on the size provided dynamically

Why this is happening?



function chunkArrayInGroups(arr, size) {
// Break it up.
var updatedarr = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < size; j++) {
updatedarr[i][j] = arr[i];
}
}
return updatedarr;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);




Answer

You can chunk your array by,

function chunkArrayInGroups(arr, size) {
  var updatedarr=[]; 
  for(var i =0;i<arr.length ;i+=size) {
    updatedarr.push([]);
    //pushing the array which gonna contain the chunk.
    for(var j=i;j<i+size;j++) { // run loop from i to i+size ex: 0->2 when i = 0.
     //picking the last chunk array and pushing the values
      updatedarr[updatedarr.length - 1].push(arr[j]);
    }
  }
  return updatedarr; 
}

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

And the output would be,

[["a","b"],["c","d"],["e","f"],["g"]]

As per the new requirement of you in your comment, you have to use break when ever you hit with an undefined.

function chunkArrayInGroups(arr, size) {
  var updatedarr=[]; 
  for(var i =0;i<arr.length ;i+=size) {
    updatedarr.push([]);
    for(var j=i;j<i+size;j++) {
      if(typeof arr[j] == "undefined") break;
      updatedarr[updatedarr.length - 1].push(arr[j]);
    }
  }
  return updatedarr; 
}

 chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);

OUTPUT:

[[0, 1, 2, 3], [4, 5]]
Comments