0

I have the following array that I need to sort by countries in alphabetical order:

data=[
    {
        "country": "China",
        "brands": {
            "abc": "123",
            "def": "123",
        },
        "day": "2020-04-16",
        "time": "2020-04-16T14:30:05+00:00"
    },
    {
        "country": "Zimbawe",
        "brands": {
            "abc": "123",
            "def": "123",
        },
        "day": "2020-04-16",
        "time": "2020-04-16T14:30:05+00:00"
    },
    {
        "country": "Africa",
        "brands": {
            "abc": "123",
            "def": "123",
        },
        "day": "2020-04-16",
        "time": "2020-04-16T14:30:05+00:00"
    }
]

I've tried this, so far:

data.sort()

and also this:

function(a, b){return a - b}

but it still returns the same order as the original array. So how do I sort this using country as the basis?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Artvader
  • 906
  • 2
  • 15
  • 31

2 Answers2

1

Use sort method

const data=[{"country": "China","brands": {"abc": "123","def": "123",},"day": "2020-04-16","time": "2020-04-16T14:30:05+00:00"},{"country": "Zimbawe","brands": {"abc": "123","def": "123",},"day": "2020-04-16","time": "2020-04-16T14:30:05+00:00"},{"country": "Africa","brands": {"abc": "123","def": "123",},"day": "2020-04-16","time": "2020-04-16T14:30:05+00:00"}];

data.sort((a, b) => a.country > b.country ? 1 : -1);

console.log(data);
.as-console-wrapper {min-height: 100% !important; top: 0;}
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
0

You can use sort with function

 data.sort(function(a, b){
   var countryA=a.country.toLowerCase(), countryB=b.country.toLowerCase();
  if (countryA < countryB)
    return -1;
  if (countryA > countryB)
    return 1; 
});
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20