0

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

Community
  • 1
  • 1
Xanarus
  • 763
  • 1
  • 6
  • 18
  • Look at the second answer by Eran and implement that in JS – Nick Zuber Mar 13 '16 at 14:30
  • Possible duplicate of [Sort an array of objects based on another array of ids](http://stackoverflow.com/questions/35538509/sort-an-array-of-objects-based-on-another-array-of-ids) – Nina Scholz Mar 13 '16 at 14:31

2 Answers2

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]; });
QED2000
  • 31
  • 2
  • ES6 does require that non-integer keys maintain the order that they were added to the object. – Barmar Jun 29 '22 at 19:49
2

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
derloopkat
  • 6,232
  • 16
  • 38
  • 45
  • Thank you! perfect, what about if we want "dontSortMe=this value doesnt need to be sorted" after "address", and not a the beginning? – Xanarus Mar 13 '16 at 20:52
  • 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(); – derloopkat Mar 13 '16 at 22:29