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]
1

1 Answer 1

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]

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

3 Comments

Arguably it's actually an empty index and not undefined
It's called sparse array.
@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”.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.