Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting object by numbers

I’m trying to sort my array one of two ways, first by overhead Ascending and then by amount Ascending.

The following code works fine for the overhead which is text but replacing a.overhead with a.amount doesn’t work correctly. It displays a 1,11,15,2,22,24,3,33,35 etc where as it should be 1,2,3,11,15,22,24 etc.

sortedArray = [...amendedArray].sort((a,b)=>(a.Overhead.toLowerCase() > b.Overhead.toLowerCase()) ? 1 : ((b.Overhead.toLowerCase() > a.Overhead.toLowerCase()) ? -1 : 0));

I believe I need to use function for numbers but I got help with the above code and I can’t seem to convert it to make it work in my scenario.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sortedArray = [...amendedArray].sort(function(a, b){ return a.Amount - b.Amount });

>Solution :

You can use a collator that can handle comparison of both strings and numbers

const collator = new Intl.Collator("en", {
  sensitivity: 'base', // ignore case and accents
  numeric: true // treat numeric strings as numbers,  "1" < "2" < "10"
});

sortedArray = [...amendedArray].sort((a, b) => {
  return collator.compare(a.Overhead, b.Overhead) || collator.compare(a.Amount, b.Amount)
})

You can read more about the Intl.Collator and the options

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading