How can I sort objects by keys consisting of alphanumeric text?

My objects key consists of alphanumeric text and I want the final object to be sorted by A1 object first then A2 object etc… when all A objects are sorted then B1, B2 etc…

const myObject = {
  "A1": {
    "sum": 1,
    "count": 1,
    "average": "1.00"
  },  
  "A13": {
    "sum": 5,
    "count": 1,
    "average": "5.00"
  },
  "A2": {
    "sum": 6,
    "count": 3,
    "average": "2.00"
  },
  "B10": {
    "sum": 4,
    "count": 1,
    "average": "4.00"
  },
  "Z5": {
    "sum": 8,
    "count": 1,
    "average": "8.00"
  },
  "B1": {
    "sum": 3,
    "count": 1,
    "average": "3.00"
  },
  "D1": {
    "sum": 2,
    "count": 1,
    "average": "2.00"
  },
  "E1": {
    "sum": 7,
    "count": 2,
    "average": "3.50"
  },
  "M1": {
    "sum": 41,
    "count": 14,
    "average": "2.93"
  }
}

Right, I made hard work of this one, but got there in the end :slight_smile:

If you want a guaranteed order, then I would have thought an array would be more suitable.

const sortAlphaNumerically = function(source) {
  return Object
    .entries(source)
    .sort(([keyA], [keyB]) => {
      return keyA.localeCompare(keyB, undefined, { numeric: true })
    })
    .map(([key, prop]) => ({[key]: prop}))
}

console.log(JSON.stringify(sortAlphaNumerically(myObject), null, 2))

Output

[
  {
    "A1": {
      "sum": 1,
      "count": 1,
      "average": "1.00"
    }
  },
  {
    "A2": {
      "sum": 6,
      "count": 3,
      "average": "2.00"
    }
  },
  {
    "A13": {
      "sum": 5,
      "count": 1,
      "average": "5.00"
    }
  },
  {
    "B1": {
      "sum": 3,
      "count": 1,
      "average": "3.00"
    }
  },
  {
    "B10": {
      "sum": 4,
      "count": 1,
      "average": "4.00"
    }
  },
  {
    "D1": {
      "sum": 2,
      "count": 1,
      "average": "2.00"
    }
  },
  {
    "E1": {
      "sum": 7,
      "count": 2,
      "average": "3.50"
    }
  },
  {
    "M1": {
      "sum": 41,
      "count": 14,
      "average": "2.93"
    }
  },
  {
    "Z5": {
      "sum": 8,
      "count": 1,
      "average": "8.00"
    }
  }
]
1 Like

Attributes of an object do not have an order. If you want to have an order you need to convert the object to an array. Because we do not know what your goal is we cannot say if this makes sense?

1 Like

Thanks for the solution but the final output should be an object instead of array of objects.e,g
{
“A1”: {
“sum”: 1,
“count”: 1,
“average”: “1.00”
},
etc…
}

Did you read my post?

Objects do not have an order so it is not possible…

1 Like

ok txs.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.