0

I have this code snippet which works

for (let [num, freq] of map) {
    let values = (bucket[freq] || new Array()) ;
    values.push(num);
    bucket[freq] = values
}

bucket is an array of lists it's iterating over map, checking if there is a list in the spot of freq, if not, it creates a new list, pushes num to the list, and pushes the list back to bucket[freq].

When I tried to do it in one line, like this

for (let [num, freq] of map) {
    bucket[freq] = (bucket[freq] || new Array()).push(num) ;
}

then bucket didn't update correctly. I can't understand what is the difference between the two approaches

I tried to write both versions, only the first worked, the other gave me incorrect answers

nameless
  • 1,483
  • 5
  • 32
  • 78
JohhnyM
  • 31
  • 5
  • 1
    Issue is because `array.push()` returns the length of the resulting array as an integer, not the array itself. – Rory McCrossan May 09 '23 at 16:06
  • As @RoryMcCrossan mentioned, push returns a new length, no the added element. You can go with two following options: `for (let [num, freq] of map) {bucket[freq] = bucket[freq] ?? [];bucket.push(num);}` `for (let [num, freq] of map) {bucket[freq] = (bucket[freq] ?? []).concat([num]);}` – wonderflame May 09 '23 at 16:08

0 Answers0