0

I have the following array of age groups:

["35 - 44", "18 - 34", "55+", "45 - 54"]

I want to sort it so that I have:

["18 - 34", "35 - 44", "45 - 54", "55+"]

What I have so far is:

arr.map(item => parseInt(item, 10)).sort((a, b) => a - b)

Which gives me:

[18, 25, 35, 65]

But I don't know what to do now with it.

Thanks for help.

1 Answer 1

3

Don't map it through parseInt, otherwise the non-numbers past the beginning of the string will be dropped. Just sort the plain array of strings with localeCompare:

console.log(
  ["35 - 44", "18 - 34", "55+", "45 - 54"].sort((a, b) => a.localeCompare(b))
);

To be a bit more flexible, if single-digit ranges exist too, use the numeric: true option as well:

console.log(
  ["35 - 44", "1-2", "3-4", "18 - 34", "55+", "45 - 54"]
    .sort((a, b) => a.localeCompare(b, undefined, {numeric: true}))
);

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

2 Comments

That's what { numeric: true } takes care of.
Sorry...missed that beyond the scrollbar ,😯

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.