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

188
Views
sort a javascript object by key : '10' is before '05'

I'm using the following function to sort an object by keys.

The problem is when I have to sort '05' and '10', the '10' is sorted before the '05'

function sortObj(obj) {
  return Object.keys(obj).sort().reduce(function(result, key) {
    result[key] = obj[key];
    return result;
  }, {});
}

let list = {
  '10': "Ann",
  '05': 75
};
let arr = sortObj(list);
console.log(arr);

Object { "10": 75, "05": "Ann" }

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Javascript objects are not ordered by insertion order. To demonstrate, change .sort() to .reverse()

Does JavaScript guarantee object property order?

Seems like you can use a map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared

about 4 years ago · Juan Pablo Isaza Report

0

Ordering an object makes little sense, because objects don't concern itself about the order it is as you access it's values by a key.

Though you can store your data in a Map which has a key-value structure that honors it's order of insertion.

function sortObj(obj) {
  return new Map(
    Object.entries(obj).sort(([a], [b]) => {
      return a - b;
    })
  );
}

let list = {
  '11': 'Beth',
  '10': "Ann",
  '05': 75,
  '07': true
};

let map = sortObj(list);
for (const [key, value] of map) {
  console.log(key, value);
}

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