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?

1

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.