skip to Main Content

this question is more for understanding and less a question that needs a solution.

I need to sort the keys of an Object in alphabetical order.
My first way was this where i push all Object.keys into an array and then trying to sort it:

keysArr.push(Object.keys(obj))
keysArr.sort()
return keysArr

which returns the array but not sorted (why?)

After trying around for a bit i came up with this solution

let sortedObjKeys = Object.keys(obj).sort()
keysArr.push(sortedObjKeys)
return sortedObjKeys

where i sort the Object.keys first and then pushing it into the array, but i dont understand why this is.

2

Answers


  1. Object.keys(obj) returns a string array of the keys of an object. Now you push that array into an array which results in a structure like this [[...]]. (See the console in the snippet below)

    const obj = {c: 0, d: 0, a: 0, b: 0};
    const keysArr = [];
    keysArr.push(Object.keys(obj));
    keysArr.sort();
    
    console.log(keysArr);

    When trying to call sort on the object you just pushed into your array it doesn’t work as expected because per default the Array#sort() method sorts stringy values (=values converted to strings) in alphabetical order ascendingly.

    From developer.mozilla.org

    The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


    Your second approach works because you filter the actual array of strings and not an array of arrays of strings. However, you could go with your first approach if you used the spread syntax which eliminates the nested array structure. E. g.:

    keysArr.push(...Object.keys(obj));
    keysArr.sort();
    
    Login or Signup to reply.
  2. Object.keys(obj) returns an array of keys, You are pushing an array of keys to your array, so you will have one array containing one element which is an array of keys.

    The sort function will not work, as there is only one element in the array, which is the object keys array.

    To fix this you should initialize the array value with object keys, not push it.

    const obj = {c: 0, d: 0, a: 0, b: 0};
    const keysArr = Object.keys(obj).sort();
    
    console.log(keysArr);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search