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.

0

1 Answer 1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.