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
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)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
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.:
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.