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];
5
  • are you certain that the first two characters would always be numbers ? Commented Jan 17, 2018 at 4:30
  • Possible duplicate of Sort mixed alpha/numeric array Commented Jan 17, 2018 at 4: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'] Commented Jan 17, 2018 at 4:32
  • or more simply .sort((a,b) => parseFloat(b) - parseFloat(a)) Commented Jan 17, 2018 at 4:37
  • Yest, the 1st two characters are derived from user inputs (type=numbers) - so always starts with numerals (either 1 or 2 digit). Commented Jan 17, 2018 at 4:51

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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;
}

2 Comments

if you know you will have integer percentages - you could always use parseFloat instead
Dang! forgot that parseFloat would strip everything but the numerals! Thank you! Worked perfectly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.