0

I'm on FCC challenge JavaScript Algorithms and Data Structures Basic Algorithm Scripting

I was expecting the following codes return same result, but just the 2nd one is passing the FCC challenge, and I'd like to understand why.

Code 1:

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  for (let i = 0; i < (arr.length); i + size) {
    console.log(`arr = ${arr}`)
    let subArr = []
    subArr.push(arr.splice(i, i + size))
    newArr.push([subArr])
  }
  return newArr
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4));

Code 2

function chunkArrayInGroups(arr, size) {
  let newArr = [];
  for (let i = 0; i < (arr.length); i + size) {
    newArr.push(arr.splice(i, i + size))
  }
  return newArr
}

console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4));

Could someone please help me understand why the different results?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Please post as a [mcve] – zer00ne Oct 17 '22 at 19:55
  • I've removed console.log statements for clarity purposes, it makes the code better for the mentioned purposes? – Luciano Soares Oct 17 '22 at 20:01
  • 1
    Cut and paste 1st code then click button with brackets `<>`. Repeat with second code. Do not remove `console.log()` lines. `splice()` mutates the original array, so every iteration you are dealing with the array as it is changed, therefore when second `splice()` is called `i` is not what you'd expect. An empty array is called within the loop is deleted and reassigned new value on each iteration. – zer00ne Oct 17 '22 at 20:05
  • 1
    Use `slice()` instead of `splice()`, so you don't remove from the array you're iterating over. – Barmar Oct 17 '22 at 20:41
  • `i+size` doesn't do anything, since you're not assigning the result anywhere. – Barmar Oct 17 '22 at 20:41
  • @zer00ne by "<>" button do you mean paste code as a code snippet? Isn't it appearing as a snippet for you? Because in my end both codes are already as snippet codes. Please let me know if I misunderstood something? – Luciano Soares Oct 19 '22 at 20:00
  • @zer00ne about splice x slice thanks for pointing out, I went to research about it and learned a bit more! – Luciano Soares Oct 19 '22 at 20:04

0 Answers0