Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
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?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

You can use JS custom sort from Array.prototype.sort(), reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Then you can sort by comparing the two element's order, but you still need to determine it's key/attribute (e.g.: a or b or c)

Here, you can use Object.keys() function and take the first key in the object, reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Here's a working example:

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



//console.log(test);


test.sort((firstEl, secondEl) => { 
    var key1 = Object.keys(firstEl)[0];
    var key2 = Object.keys(secondEl)[0];
    return firstEl[key1].order - secondEl[key2].order
} );
console.log(test);

Output:

[
  {
    "c": {
      "order": 1
    }
  },
  {
    "b": {
      "order": 10
    }
  },
  {
    "a": {
      "order": 100
    }
  }
]
about 4 years ago · Santiago Gelvez Report

0

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

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!