3

The current output of my array is:

"10 FOOT", "45 RPM", "9 VOLT", "910D0", "AGUA", "BEAST", "KEN 5", "NEMCO"

What I want is:

"AGUA", "BEAST", "KEN 5", "NEMCO", "9 VOLT", "10 FOOT", "45 RPM:, "910D0"

How do I achieve this?

7
  • why would a number at the end have precedence over sorting alpha numerically? No wait, what has actually that number at the end have anything to do with the question? Commented Apr 4, 2021 at 12:24
  • does this post solve your question? stackoverflow.com/questions/18939726/… Commented Apr 4, 2021 at 12:25
  • You need to explain more about your sorting criteria... Commented Apr 4, 2021 at 12:28
  • 1
    Let's clarify a bit, is this what you want? If an element starts with a letter, sort it alphabetically. If it starts with a number, sort it by the value of the number (not only the first digit), and finally, those starting with a number should go after the ones starting with a letter? Commented Apr 4, 2021 at 12:30
  • Please post compilable code. Those quotes throw an error. Commented Apr 4, 2021 at 12:31

4 Answers 4

3

You could check if the string starts with a digit and sort the rest by groups.

const array = ['10 FOOT', '45 RPM', '9 VOLT', '910D0', 'AGUA', 'BEAST', 'KEN 5', 'NEMCO'];

array.sort((a, b) => isFinite(a[0]) - isFinite(b[0])
    || a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
);

console.log(array);

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

Comments

2

const order = ["10 FOOT", "45 RPM", "9 VOLT", "910D0", "AGUA", "BEAST", "KEN 5", "NEMCO"];

order.sort((a, b) => /^[0-9]/.test(a) - /^[0-9]/.test(b) || a.localeCompare(b, undefined, { numeric: true }));

console.log(order);

Sort elements starting with a number first, afterwards use localeCompare's numeric option (which ensures "10" > "2").

Comments

0

You could create 2 new arrays, sort them and put them back together:

const arr = ["10 FOOT", "45 RPM", "9 VOLT", "910D0", "AGUA", "BEAST", "KEN 5", "NEMCO"];
const nums = arr.filter(a => parseInt(a))
const words = arr.filter(a => !parseInt(a))

nums.sort((a,b) => parseInt(a) -parseInt(b))
words.sort()

const finalArray = words.concat(nums)

Comments

-1

const arr = ["10 FOOT", "45 RPM", "9 VOLT", "910D0", "AGUA", "BEAST", "KEN 5", "NEMCO"];

const customCompare = (a, b) => 
  /^\d/.test(a) - /^\d/.test(b) || 
  a.localeCompare(b, undefined, { numeric: true });

const sorted = arr.sort(customCompare);

console.log(...sorted);

Comments

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.