Skip to content Skip to sidebar Skip to footer

Sorting Data By Object Keys Does Not Work When Some Of The Keys Are Numeric

I have object contain data like this const testData = { '11': { 'data': { 'firstName': 'firstName', 'lastName': 'lastName'

Solution 1:

You cannot. The defined iteration order for JavaScript object keys is as follows:

  1. Numeric keys, in ascending numeric order. (this includes strings such as "11", but not "01"), THEN...
  2. String keys which are not numeric, in order of insertion. THEN...
  3. Symbol keys, in order of their insertion.

As you can see, regardless of insertion order, numeric keys will always appear first in the iteration order, and always in their numeric order.

In your example, "11" and "12" will always end up first, regardless of what you do.

In general, relying on order with objects (which are essentially unordered dictionaries you access via key), is ill-advised. If order matters, you should be using an array. Alternatively, you can use a Map.


Solution 2:

Try something like this:

sorted = Object.keys(testData).sort((a,b) => {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
});

console.log(sorted)

Post a Comment for "Sorting Data By Object Keys Does Not Work When Some Of The Keys Are Numeric"