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.

1
  • Maybe my answer here will help. Let me know if you need more help (don't forget to start with @...) Commented Jun 5, 2018 at 11:26

2 Answers 2

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

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

1 Comment

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 for composing a sorter function.
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()

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.