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?
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?
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);
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").
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);
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)