简体   繁体   English

如何按字母顺序对 javascript 数组进行排序,最后是数字(字母之后),并正确地按数字排序?

[英]How to sort a javascript array alphabetically with numbers at the end (after letters), and correctly sorting numerically?

The current output of my array is:我阵列的当前 output 是:

"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.您可以检查字符串是否以数字开头并按组对 rest 进行排序。

 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").首先对以数字开头的元素进行排序,然后使用 localeCompare 的数字选项(确保“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:您可以创建 2 个新的 arrays,对它们进行排序并将它们重新组合在一起:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM