skip to Main Content

I have the following:

{Object.keys(categorizedDatas3).map((key, index) => {

categorizedDatas3 looks like this:

{
    "Boat": {
        "items": [
            {
                "Quantity": 1,
                "Name": "AAA"
            },
            {
                "Quantity": 1,
                "Name": "BBB"
            }
        ]
    },
    "4x4": {
        "items": [
            {
                "Quantity": 1,
                "Name": "CCC"
            }
        ]
    }
}

How can I sort the key A-Z (i.e. I always want 4×4 items to appear before Boat items)?

2

Answers


  1. You can use the Array.prototype.sort method to sort the array.
    In order to sort the array alphabetically, you can use the String.prototype.localeCompare method.

    I took the answer from this other answer. In your case it would be:

    {Object.keys(categorizedDatas3)
      .sort((a, b) => a.localeCompare(b))
      .map((key, index) => 
        /* your element */
    )}
    
    Login or Signup to reply.
  2. Why don’t you try lodash sortBy?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search