javascript - 在javascript中对数组进行排序的算法
问题描述
我很难找到解决方案。
我有一个类似的数组。
// Original array
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];
// The sorted array needs to be like this.
sorted_array = ["1", "1A", "01A", "2", "02B", "03B", "10"];
我曾尝试编写这样的自定义排序函数,但找不到解决方案。我很感激任何帮助。
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];
const sorted_array = orig_array.sort((a, b) => {
if (a - b) {
return a - b;
}
if (a.localeCompare(b) === -1) {
return a.length - b.length;
} else {
return 1;
}
});
console.log(sorted_array);
解决方案
您可以首先应用parseInt
到两个字符串以获取第一个数字部分并减去它们。如果数字部分相等,则减去长度。
const orig_array = ["2", "10", "01A", "1A", "02B", "1","03B"];
console.log(orig_array.sort((a,b)=>parseInt(a)-parseInt(b)||a.length-b.length));
推荐阅读
- javascript - removeCue() 函数后如何刷新 TextTrack
- sql-server - 在 SELECT 语句中编写完整路径会提高 SQL 的性能吗?
- html - 如何跨 JSON (AngularJS) 创建集合
- applescript - Applescript 处理程序,重复 i 从 1 到 this_list 的编号
- powerbi - Power BI 中的日期列分为 4 列
- node.js - 为什么我们需要 node 应用程序根目录的 package.json 中的 main 属性,如果它是为了告诉包和模块的入口点?
- python - 如何计算子目录中的文件数?
- kubernetes-ingress - GKE 上的一个 GCE 入口导致另一个 GCE 入口为默认后端提供服务
- sql - SQL Server 存储过程选择参数传递的特定列,并检查其他约束
- ruby - 为什么我在明显存在的对象上得到“nil:NilClass 的未定义方法”?