1

I have a problem, I don't understand why arr.slice doesn't work when the first value is 0, the returned array is empty:

function chunkArrayInGroups(arr, size) {
  var newArr = [];

  for (var i = 0; arr[i]; i += size) {
    newArr.push(arr.slice(i, i + size));
  }
  return newArr;
}
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));

3
  • 1
    What's this: for (var i = 0; arr[i]; i += size) {? Commented Oct 18, 2016 at 7:29
  • what result do you expect? Commented Oct 18, 2016 at 7:32
  • 1
    Falsy values Commented Oct 18, 2016 at 7:32

4 Answers 4

5

You end direct the loop with the condition, which evaluates as false.

arr[i] -> arr[0] -> 0 -> false -> end for loop

Use the length of the array as check

for (var i = 0; i < arr.length; i += size) {
//              ^^^^^^^^^^^^^^

function chunkArrayInGroups(arr, size) {
  var newArr = [];

  for (var i = 0; i < arr.length; i += size) {
    newArr.push(arr.slice(i, i + size));
  }
  return newArr;
}
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));

Sign up to request clarification or add additional context in comments.

2 Comments

But why it's evaluates as false ? I want to access in array case, why arr[0] doesn't work when it's value is 0 ?
Ok I understand, my bad ^^" arr[i] block my loop... I correct this to i < arr.length. thank you
0

try with this

  function chunkArrayInGroups(arr, size) {
  // Break it up.
  var  newArr = [];

 for (var i = 0; typeof arr[i]!='undefined'; i += size) {
  newArr.push(arr.slice(i, i + size));
 }
  return newArr;
 }
chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)

Comments

0

The problem is arr[i] not arr.slice.

First Element of [0, 1, 2, 3, 4, 5 ,6] is 0 and it is false.

Just use other conditions like i < arr.length in for statement.

Comments

-1

for (var i = 0; arr[i]; i += size) , arr[0] is 0, means false, so the loop is never entered

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.