How to sort a Javascript object, or convert it to an array?
Array.prototype.slice.call(arrayLikeObject)
is the standard way to convert and an array-like object to an array.
That only really works for the arguments
object. To convert a generic object to an array is a bit of a pain. Here's the source from underscore.js:
_.toArray = function(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); if (_.isArray(iterable)) return iterable; if (_.isArguments(iterable)) return slice.call(iterable); return _.values(iterable);};_.values = function(obj) { return _.map(obj, _.identity);};
Turns out you're going to need to loop over your object and map it to an array yourself.
var newArray = []for (var key in object) { newArray.push(key);}
You're confusing the concepts of arrays and "associative arrays". In JavaScript, objects kind of act like an associative array since you can access data in the format object["key"]
. They're not real associative arrays since objects are unordered lists.
Objects and arrays are vastly different.
An example of using underscore:
var sortedObject = _.sortBy(object, function(val, key, object) { // return an number to index it by. then it is sorted from smallest to largest number return val;});
See live example
You should be able to convert a JavaScript object into an array like so...
var obj = { '1': 'a', '2': 'b', '3': 'c' };var arr = [];for (var key in obj) { if (obj.hasOwnProperty(key)) { arr.push(obj[key]); }}console.log(arr); // ["a", "b", "c"]
If your JavaScript object is an array-like object, that is, an Object instance with a valid numerical length
property, then you can directly use many native Array methods on it thanks to the call
method. For example:
// Sorts the given objet in-place as if it was an arrayArray.prototype.sort.call(yourObject);
So if you know the number of entries to be sorted (How to efficiently count the number of keys/properties of an object in JavaScript?), you can do:
yourObject.length = theNumberOfEntries;Array.prototype.sort.call(yourObject);// Optionally: delete yourObject.length;
Note that this will only sort properties indexed by "0", "1", "2", ... to length - 1
inclusive, like in an Array. The object's other properties will not be re-ordered.