How do you sort an object by keys based on another array in Javascript?
This is the same question as here PHP Sort an Array by keys based on another Array?
But I need the same process for Javascript.
Thanks
How do you sort an object by keys based on another array in Javascript?
This is the same question as here PHP Sort an Array by keys based on another Array?
But I need the same process for Javascript.
Thanks
The JavaScript specification does not require that object keys maintain their order, so it is not safe to attempt to sort them. It is up to each environment to implement the standard, and each browser does this differently. I believe most modern browsers will sort keys on a first-in-first-out basis, but since it is not part of the standard, it is not safe to trust this in production code. It may also break in older browsers. Your best bet is to place your object keys into an array, sort that array and then access the values of the object by the sorted keys.
var myObject = { d: 3, b: 1, a: 0, c: 2 },
sortedKeys = Object.getOwnPropertyNames(myObject).sort();
You could then map the ordered values into a new array if you need that.
var orderedValues = sortedKeys.map(function (key) { return myObject[key]; });
As QED2000 pointed out, even if you create a new object, there's no guaranty that the properties will remain in a specific order. However you can sort the keys depending on a different array.
<script>
function sortArrayByArray(a, b)
{
return order.indexOf(a) - order.indexOf(b);
}
var order = new Array('name', 'dob', 'address');
var customer = new Array();
customer['address'] = '123 fake st';
customer['name'] = 'Tim';
customer['dob'] = '12/08/1986';
customer['dontSortMe'] = 'this value doesnt need to be sorted';
var orderedKeys = Object.keys(customer).sort(sortArrayByArray);
orderedKeys.forEach(function (key) {
document.write(key + "=" + customer[key] + "<br/>");
});
</script>
The output is
dontSortMe=this value doesnt need to be sorted
name=Tim
dob=12/08/1986
address=123 fake st