Chunky Monkey : undefined values in array

Chunky Monkey : undefined values in array
0.0 0

#1

When i run the test i get undefined values in my array and don’t know how to get rid of them.

[ab , undefinedcd]
when it should return [ab, cd];

i can post my code if that helps;


#2

Yeah, we can’t tell you what’s wrong in your code without actually seeing your code.


#3
function chunkArrayInGroups(arr, size) {
  var newarr=[[]];
  
  for(var i=0; i<( (arr.length)/size) ; i++){
    for (var j=0; j<size; j++){
      newarr[i]+=arr[(size*i)+j]; 
    }
  }
  return newarr;
}

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

#4

Here is an updated version

function chunkArrayInGroups(arr, size) {
var newarr=[[]];
var l=arr.length/size;
for(var i=0; i<l ; i++){
for (var j=0; j<size; j++){
newarr[i]+=arr[ (l*i)+j];

}

}

return newarr;

}

chunkArrayInGroups([“a”, “b”, “c”, “d”], 2);


#5

The problem comes from newarr[i]+=. On the second iteration of your outer loop you are referring to newarr[1] but newarr has no second element so newarr[1] is undefined. You then add contents of arr to undefined.


#6

Thanks for the help
I’m used to java and c++ and trying to apply those methods to javascript does’nt quite work


#7

JavaScript is… funky.