0
I would like to sort array of arrays with the name parameter.

Array data is like below, which is having the id and name. i would like to sort the array based on the name.

myArray = [
{
    "id": 412,
    "name": "r1",
},
{
    "id": 116,
    "name": "Apply All ",
},
{
    "id": 117,
    "name": "Apply Critical ",
},
{
    "id": 118,
    "name": "a",
},
{
    "id": 119,
    "name": "c",
},
{
    "id": 120,
    "name": "b",
},
]

I tried the following code but it is not helping

function Comparator(a, b) {
   if (a[1] < b[1]) return -1;
   if (a[1] > b[1]) return 1;
  return 0;
}

 myArray = myArray.sort(Comparator);
 console.log(myArray);

Any help in arranging the array with the name key.

mvsr
  • 29
  • 5

1 Answers1

0

You need to pass the key instead of the index:

myArray = [
{
    "id": 412,
    "name": "r1",
},
{
    "id": 116,
    "name": "Apply All ",
},
{
    "id": 117,
    "name": "Apply Critical ",
},
{
    "id": 118,
    "name": "a",
},
{
    "id": 119,
    "name": "c",
},
{
    "id": 120,
    "name": "b",
},
]

function Comparator(a, b) {
   if (a["name"] < b["name"]) return -1;
   if (a["name"] > b["name"]) return 1;
  return 0;
}

 myArray = myArray.sort(Comparator);
 console.log(myArray);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48