4

I use next code for 500k+ array elements and gets max call stack error:

function getSortedUniqInts(arr) {
  const unique = new Set(arr);
  return new Array(...unique).sort((a, b) => a - b);
}

But this code works without the error:

function getSortedUniqInts(arr) {
  const unique = new Set(arr);
  return [...unique].sort((a, b) => a - b);
}

What is the difference between these?

Vladimir Mironov
  • 185
  • 1
  • 1
  • 9
  • On each sort your are initialising the new array which which hit the stack and give error at some point – Sohan Dec 14 '21 at 13:39
  • @Sohan _"On each sort your are initialising the new array..."_ - That's the case in both versions – Andreas Dec 14 '21 at 13:40
  • 1
    https://stackoverflow.com/questions/7375120/why-is-arr-faster-than-arr-new-array – Roberto Zvjerković Dec 14 '21 at 13:48
  • Cannot reproduce (with FF): https://jsfiddle.net/b5svkz6r/ - The only error I get with more than 500000 elements: `RangeError: too many constructor arguments` – Andreas Dec 14 '21 at 13:48
  • 1
    https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar – Roberto Zvjerković Dec 14 '21 at 13:50
  • 1
    @Andreas "RangeError: too many constructor arguments" is at least part of the answer. `new Array(...set)` is a function call with `set.length` number of parameters, while `[...set]` is probably handled much more efficiently by most JS engines. – Inigo Dec 14 '21 at 14:10
  • 2
    Chromium chrashes with that call stack error when the array has more than ~60000 entries. – Andreas Dec 14 '21 at 14:20
  • See [What is the use case for Javascript's (ES6) Array.of()?](https://stackoverflow.com/q/31686360/1048572) for why it doesn't work with only a single element. Then use `Array.from(unique)`, which is exactly equivalent to `[...unique]`. – Bergi Dec 14 '21 at 14:28

0 Answers0