Spreading an object into an array and sort order

Intermediate Algorithm Scripting: Seek and Destroy

Will an object like this when spread into an array:

{ ‘0’:‘A’, ‘1’:‘B’, ‘2’:‘C’, ‘3’:‘D’ }

always result in an array like this:

[‘A’,‘B’,‘C’,‘D’]

ordered by the keys in the original object ?

This seems to have worked in this problem, but I want to make sure there is some sort of guarantee or rule that applies to spreading an object into an array.

This is what I did:

let args = […arguments];

args is now an array in the right order based on the keys in the original arguments object.

Thanks,

Warren

You can rely on order in the arguments object but property order is not guaranteed for objects in general. So yeah, what you did is safe.

I don’t think that what you have done here would work for most other objects anyways. It works because arguments is “array-like” supporting the spread operator such that it spreads like an array into a comma separated list of values without property names. The not-yet-standard for spread of object literals expands both properties and the values

I used the term “deconstructing” when I meant “spread”.

arguments is an array-like object, it’s ordered. It’s basically a very lightweight array (without the methods etc). If you think about this logically, if you couldn’t depend on the order, then how would the language work?

let args = […arguments];

In this case, you’re using spread syntax on an iterable. An iterable is a thing that implements the iterable protocol: out-of-the-box, Arrays & their derivatives [eg args, DOM collections], Maps, Sets, Strings). And also need to implement the Iterator protocol, which allows you to return the values one-by-one. So

args is now an array in the right order based on the keys in the original arguments object.

Yes. ...arguments is going to iterate over and return the values one-by-one, and you’re collecting them into an array.

Note @alhazen1

The not-yet-standard for spread of object literals expands both properties and the values

Very recent, but Object syntax is standardised now, has been for a year (ES2018).