-4

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.

sortedArray = [...amendedArray].sort(function(a, b){ return a.Amount - b.Amount });
Dan
  • 1,565
  • 3
  • 23
  • 43

1 Answers1

-3

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

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317