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

96
Views
Sort a key and value in a javascript object using ES6

I have an object whose keys are dynamically generated by the data receoved from the api response.

code:

var object = {
ABS-Test: 11,
CAS-tab-Running: 9,
ABS-tag-objetc: 9,
Internet-Facing-ABS: 9,
ABS-connector-test: 11
}

How can I sort using the object above based on value and key. Example of the expected output when sorted based on key of the object;

var sortedObject = {
    ABS-connector-test: 11,
    ABS-tag-objetc: 9,
    ABS-Test: 11,
    CAS-tab-Running: 9,
    Internet-Facing-ABS: 9
    }


var sortedValueObject = {
    ABS-tag-objetc: 9,
    CAS-tab-Running: 9,
    Internet-Facing-ABS: 9,
    ABS-connector-test: 11,
    ABS-Test: 11,
    }

I have referred Sort a JavaScript object by key or value; ES6 and SO far I have this for sorting by value:

sorted_object = Object.entries(unsorted_object)
  .sort(([,v1], [,v2]) => +v2 - +v1)
  .reduce((r, [k, v]) => Object.assign(r, { [k]: v }), {});

and this for sorting by key:

sorted_object = Object.entries(data)
  .sort((a, b) => a[1] - b[1])
  .reduce((a, [key, val]) => {
    a[key] = val;
    return a;
  }, {});

Both of them return output in certain order (either ascendeing or desc). Do we have a logic or a lodash method that'll help to toggle the sorting logic based on the asc or desc value provided?

I tried via the _orderBy() and _sortBy() from lodash Reactjs, however they require a static key value to be passed to get the results.

about 4 years ago · Juan Pablo Isaza
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!