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

171
Views
React - Sort object entries by key in a specific order

I have an object

{
   "undefined": 10, 
   "women": 5,
   "men": 3,
}

And I need to sort it, so it looks like

{
   "men": 3,
   "women": 5,
   "undefined": 10, 
}

How can I do it?

I have tried to sort it like that, but it works alphabetically.

const object = {
  "undefined": 10,
  "women": 3,
  "men": 6
}

const entries = Object.entries(object).sort();

const sortedObject =  Object.fromEntries(entries);

console.log(sortedObject);

/*
   Expected result: 
   
   {
     "men": 6,
     "women": 3,
     "undefined": 10
   }
*/

This is what I am trying to do:

statsParser.js

import { t } from "i18n";

export default (genders) => {
  if (!genders) return;

  const entries = Object.entries(genders).sort(([, a], [, b]) => b - a); // What if I want to order the map so it looks like { men: x, women: y, undefined: z } instead of by value in desc order?

  const translatedEntries = entries.map((entry) => [
    t(`content.stats.genders.${entry[0].toLowerCase()}`),
    entry[1],
  ]);

  const translatedGenders = Object.fromEntries(translatedEntries);

  return translatedGenders;
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

To sort json object using key is easy as below:

const unordered = {
   "undefined": 10, 
   "women": 5,
   "men": 3,
}    
const ordered = Object.keys(unordered).sort().reduce(
  (obj, key) => { 
    obj[key] = unordered[key]; 
    return obj;
  }, 
  {}
);

console.log(JSON.stringify(ordered));

To sort json object using value, you need convert your object into array using Object.entries. Then you sort that array using value and prepare string using map function and finally parse it into json.

const unordered = {
   "undefined": 10, 
   "women": 5,
   "men": 3,
}
const arrOfArrays = Object.entries(unordered);

const ordered = arrOfArrays.sort((a, b) => {
    const aVal = Object.values(a)[1];
    const bVal = Object.values(b)[1];
    return aVal - bVal;
  }); 

var jsonString = "{";
ordered.map(obj => {
  var json = { ...obj };
  jsonString += `"${json[0]}":"${json[1]}",`;
});
jsonString = jsonString.replace(/,\s*$/, "");
jsonString += "}";

console.log(JSON.parse(jsonString));
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!