Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort double objects?

I have an array. The data in the array is in the following format.

var test = [
    {
    "a" : {
        "order" : 100,
    }
  },
  {
    "b" : {
        "order" : 10,
    }
  },
  {
    "c" : {
        "order" : 1,
    }
  },
];

I want to sort this data according to order value. Is there any way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Object.values to get the first property value and access the order property on that to compare.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
test.sort((a, b)=>Object.values(a)[0].order - Object.values(b)[0].order);
console.log(test);

For a more generalized solution, you can create a key extractor function to get the value to compare by.

let test=[{a:{order:100}},{b:{order:10}},{c:{order:1}}];
const getOrder = x => Object.values(x)[0].order;
test.sort((a, b)=>getOrder(a) - getOrder(b));
console.log(test);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading