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

93
Views
sorting an object by value type

I am trying to sort an Object from

{"key4": {"name":"joe"},"key3": ["aaa", "bbb"],"key5": {"aaa":["name","joe"]}, "key1": "TypeString", "key2": 0}

to

{"key1": "TypeString", "key2": 0, "key3": ["aaa","bbb"], "key4": {"name":"joe"},"key5": {"aaa":["name","joe"]}}

my main goal is to sort by the value type and not the the value its self.. ie each value with the type string comes first followed by int then arrays and final object.

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

0

When you print an object, the order of keys is implementation dependent. If you really need to get the keys in insertion order, you can use Reflect.ownKeys() (for details, see MDN):

const obj = {"key4": {"name":"joe"},"key3": ["aaa", "bbb"],"key5": {"aaa":["name","joe"]}, "key1": "TypeString", "key2": 0};

const keys = Object.keys(obj);
const keysSorted = keys.sort((key1, key2) => getTypeSortId(obj[key1]) - getTypeSortId(obj[key2]));
const objSorted = keysSorted.reduce((o, key) => (o[key] = obj[key], o), {});
console.log(objSorted);
console.log(Reflect.ownKeys(objSorted));

function getTypeSortId(value) {
  return (
    typeof value === "string" ? 1 :
    typeof value === "number" ? 2 :
    value instanceof Array ? 3 :
    typeof value === "object" ? 4 :
    5
  );
}

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!