1

I have an object with numeric keys that I would like to convert to an array. Trouble is, the keys may not be contiguous, i.e. some of the array elements may be missing. Is there some simple way to do this?

Example:

const raggedArrayObj = {"0": 10, "1": 3, "3": 5}
const raggedArray = toArray(raggedArrayObj) // [10, 3, , 5]
Adam B.
  • 788
  • 5
  • 14

1 Answers1

1

Just use Object.assign():

const raggedArrayObj = { "0": 10, "1": 3, "3": 5 };
const raggedArray = Object.assign([], raggedArrayObj);

console.log(raggedArray); // [10, 3, undefined, 5]
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • Arguably it's actually an empty index and not undefined – pilchard Jan 16 '23 at 01:53
  • It's called sparse array. – Vsevolod Golovanov Jan 24 '23 at 20:39
  • @VsevolodGolovanov The index itself can be called “empty index”. Technically, on an Array object which has non-zero length _ℓ_, an “empty index” _k_ is just the lack of an own property, where the key of the property is the stringified integer _k_ with 0 ≤ _k_ ≤ min(_ℓ_ − 1, 2⁵³ − 1). The _array_ which has such an empty index can then be called “sparse array”. – Sebastian Simon Jan 24 '23 at 21:47