0

I have an object which has both numerics and alphabets like below:

{
  cc:
    {
        text:"Vienna",
        text:"Austria",
        text:"Germany",
        text:"245",
        text:"121",
    }
}

I want to sort them and this is what I have done:

cc.sort((a,b) => a.text > b.text ?1 :-1

But it is not working.

Can anyone help me?

Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35
  • Maybe you can take a look at this: https://stackoverflow.com/questions/54298232/sorting-an-array-of-objects-alphabetically – shadowraz Jul 20 '21 at 04:27

1 Answers1

1

Your data isn't "valid" JSON as the property names are not unique.

The resulting object below will have a single property "cc" that contains a single property "text" with value "121". Each time you declare the "text" property you will supersede the previous property of the same name.

{
    cc: {
        text: "Vienna",
        text: "Austria",
        text: "Germany",
        text: "245",
        text: "121",
    }
}

You could store the values in an array and sort it.

Also, bear in mind that you are storing numeric values in a string so bear this in mind and research "natural sorting".

const data = ["Vienna", "Austria", "Germany", "245", "121"]

data.sort();

console.log(data);
Robin Webb
  • 1,355
  • 1
  • 8
  • 15