1

If I have the following array:

var num = [10% cats, 20% dogs, 30% fish, 40% turtles];

where a pct value is always concatenated to a label. Is there an easy way to ort from largest percentage to smallest? Unlike other similar questions, the format here is always xx% label

using .sort() in the usual .sort(function(a,b) {return b-a;}): doesn't work since these are not numerals?

output should be:

num = [40% turtles, 30% fish, 20% dogs, 10% cats];
user1837608
  • 930
  • 2
  • 11
  • 37
  • are you certain that the first two characters would always be numbers ? – Karan Shishoo Jan 17 '18 at 04:30
  • Possible duplicate of [Sort mixed alpha/numeric array](https://stackoverflow.com/questions/4340227/sort-mixed-alpha-numeric-array) – Shafin Mahmud Jan 17 '18 at 04:31
  • 2
    `.sort((a,b) => Number(b.split('%')[0]) - Number(a.split('%')[0]))` - that assumes that `var num` is fixed to be a valid array of strings `['10% cats', '20% dogs', '30% fish', '40% turtles']` – Jaromanda X Jan 17 '18 at 04:32
  • or more simply `.sort((a,b) => parseFloat(b) - parseFloat(a))` – Jaromanda X Jan 17 '18 at 04:37
  • Yest, the 1st two characters are derived from user inputs (type=numbers) - so always starts with numerals (either 1 or 2 digit). – user1837608 Jan 17 '18 at 04:51

2 Answers2

2

You can use localeCompare for sorting specifying the numeric option.

var num = ['10% cats', '20% dogs', '40% turtles', '30% fish'];
num.sort((a,b) => b.localeCompare(a, undefined, {numeric:true})); 
console.log(num);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

You can use a sort function that converts the strings into numerical values before comparing them to sort by percentages.

var num = ['10% cats', '20% dogs', '30% fish', '40% turtles'];

num.sort( sortByPercentage );

console.log( num );

function sortByPercentage( a,b ) {
  a = parseFloat(a);
  b = parseFloat(b);
  return b-a;
}
JasonB
  • 6,243
  • 2
  • 17
  • 27