1

How to sort below List ranges in ascending order.

ranges= (1-10, 11-20, 201-500, 21-50, 501-99999, 51-200)

Tried with ranges.sort() and it is not working.

1
  • 1
    Pull out the first value - 1, 11, 21 etc... convert to number and sort on that. Mar 18, 2020 at 5:57

1 Answer 1

4

You need to split(on the basis of "-"), pull out starting element, convert it to number and sort on that.

Example

const input = ["1-10", "11-20", "201-500", "21-50", "501-99999", "51-200"];

const sortedList = input.sort((range1, range2) => startIndex(range1) - startIndex(range2));

function startIndex(range) {
    return Number(range.split("-")[0].trim());
}
1
  • 1
    input.sort((range1,range2) => startIndex(range1)-startIndex(range2)) works, too.
    – sfdcfox
    Mar 18, 2020 at 10:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .