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

243
Views
I use this function to order a nested array in JavaScript but im failing to order numerical values

I use this function to order nested arrays of objects (JSON) in Javascript (English isnt my native lang)

 nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
    const a = prop2 ? e1[prop1][prop2] : e1[prop1],
        b = prop2 ? e2[prop1][prop2] : e2[prop1],
        sortOrder = direction === "asc" ? 1 : -1
    return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
}

previously i cleaned all the null values of the array with this function

array = JSON.parse(JSON.stringify(array), (key, value) => value === null ? '' : value);

the trouble im having is that is only ordering string values and date values, the numerical values are treated like strings, i need some advice on what can i add to the nestedSort function to work dinamically ordering : strings, dates, and numerical values?

i call the function with this code

objJson = objJson.sort(nestedSort(value, null, records_order));

[Solved] Idk if it was the best way, i will appreciate if someone has a better way to do it

 nestedSort = (prop1, prop2 = null, direction = 'asc') => (e1, e2) => {
    const a = prop2 ? e1[prop1][prop2] : e1[prop1],
        b = prop2 ? e2[prop1][prop2] : e2[prop1],
        sortOrder = direction === "asc" ? 1 : -1
        if (isNaN(a) && isNaN(b)){
          return (a < b) ? -sortOrder : (a > b) ? sortOrder : 0;
        }else{
          return sortOrder == 1 ?  (a - b) : (b - a);
        }
}
about 4 years ago · Santiago Trujillo
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!