0

I have an array of Objects as below.

options: [
          {value: 1, label: "test1"},
          {value: 2, label: "test12"},
          {value: 0, label: "test123"}
         ]

I want to sort this array based on value property of the object. please let me know can I achieve it in Javascript.

Sisir
  • 33
  • 1
  • 5
  • Maybe my answer [here](https://stackoverflow.com/a/48942106/1641941) will help. Let me know if you need more help (don't forget to start with @...) – HMR Jun 05 '18 at 11:26

2 Answers2

2

You can use sort like this:

data.sort((a, b) => a.value - b.value);

Demo:

let data =  [
    {value: 1, label: "test1"},
    {value: 2, label: "test12"},
    {value: 0, label: "test123"}
];

data.sort((a, b) => a.value - b.value);

console.log(data);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • 1
    `data.sort((direction => (a, b) => (a.value - b.value)*direction)(-1));` for descending and `data.sort((direction => (a, b) => (a.value - b.value)*direction)(1));` for ascending order. I usually refer to [this answer](https://stackoverflow.com/a/48942106/1641941) for composing a sorter function. – HMR Jun 05 '18 at 11:34
0

You can sort

let options = [{
    value: 1,
    label: "test1"
  },
  {
    value: 2,
    label: "test12"
  },
  {
    value: 0,
    label: "test123"
  }
]

options.sort((a, b) => a.value - b.value);

console.log(options);

Doc: sort()

Eddie
  • 26,593
  • 6
  • 36
  • 58