1

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

2

2 Answers 2

3

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]; });
Sign up to request clarification or add additional context in comments.

1 Comment

ES6 does require that non-integer keys maintain the order that they were added to the object.
3

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

2 Comments

Thank you! perfect, what about if we want "dontSortMe=this value doesnt need to be sorted" after "address", and not a the beginning?
In that case the script starts with: function sortArrayByArray(a, b) { return order.indexOf(b) - order.indexOf(a); }; var order = new Array('name', 'dob', 'address').reverse();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.