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

How to sort numbers from high to low without looking if it's negative or positive

sortByAmountHighToLow(trades) {
  return trades.sort((a, b) => {
    return b.total - a.total;
  });
},

I have this right now (in Vue) which sorts an array of numbers from high to low, as it should.

What I instead need is a sorting function which does not look at negative numbers differently from positive numbers.

This is the output I would like (high to low):
[-531, 245, -195, 54, -12]

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

I’m getting:
[245, 54, -12, -195, -513]

I hope this clearly explains what I need.

>Solution :

I wouldn’t say that the original functions treats negatives differently

But this it what you want:

const array = [245, 54, -12, -195, -513]

array.sort((a, b) => Math.abs(b) - Math.abs(a))

console.log(array)
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