Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] [Javascript] Shouldn't there be a sort option on objects



Dave M G writes:

 > I went to Stack Overflow and looked at relevant questions/answers there,
 > and, to quote directly: "All JavaScript objects are basically
 > associative arrays"
 > http://stackoverflow.com/questions/1948936/how-do-i-convert-this-object-to-an-array-in-javascript
 > 
 > So they're already arrays, but I can't use array functions on them?

You can use *some* array functions on them, in particular indexing
(which is what makes something an array, in practice).  However, in an
ordinary array the indicies are integers, and therefore ordered.  It
makes sense to reorder the values to correspond to indicies in order.

In an associative array, the index is an arbitrary object.  Often a
string, or a symbol, but it could also be a code object or something
with a lot of internal structure, and in general there is no sense in
which these are ordered.  This means that some functions that work on
ordinary arrays won't work.  So in particular you can't use a sort
function on an associative array.  Another example is that you can't
do a binary search on an associative array.[1]

You could argue that if all of the indicies are actually ordered, you
should be able to sort the array, but that turns out to be a great way
to have your program crash the whole server when somehow something
unordered becomes an index and your program throws an unexpected
"can't sort" fatal error.  So even dynamic languages like Python and
Javascript will look at the associative array and say, "nope, not
touching *that*! not even gonna try."  (I wouldn't be surprised if
Perl can sort such a thing, though. :-)

As to how to convert such an object to an ordinary array, I don't know
offhand.  The most efficient way would be to avoid creating an object
in the first place, and read the data into an array instead of an
object.

Footnotes: 
[1]  Binary search looks like "find the object halfway between 'a
banana' and 'the color red', and check if it's the one we want; if
not, try the object halfway between 'a banana' and the object we just
found, and repeat the halving process until we find the one we want".
I hope you will agree that "halfway between 'a banana' and 'the color
red'" makes no sense, and that the computer is well within its rights
to throw a fatal error there!



Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links