2

I am trying to sort an array based on a value. I have an array for example

arr = [{t1: 'test1', t2: 'bca' },
       {t1: 'test2', t2: 'cab'},
       {t1: 'test', t2: 'abc'}]

I want to sort above array based on the value t2 in alphabetical order. the array after sorting should look like below.

arr = [{t1: 'test', t2: 'abc' },
       {t1: 'test1', t2: 'bca'},
       {t1: 'test2', t2: 'cab'}]

Please guide me how can i achieve this. THanks in advance.

r669
  • 33
  • 5

1 Answers1

0

You need to customize the sort function of an array

arr = [{
    t1: "test1",
    t2: "bca"
  },
  {
    t1: "test2",
    t2: "cab"
  },
  {
    t1: "test",
    t2: "abc"
  },
];

arr.sort(function(x, y) {
  if (x.t2 < y.t2) {
    return -1;
  }
  if (x.t2 > y.t2) {
    return 1;
  }
  return 0;
});

console.log(arr);
DecPK
  • 24,537
  • 6
  • 26
  • 42