javascript - Sort array of objects with dots, letters, numbers. I was able to sort by numbers, but mixed values are difficult. N

I tried the typical sort function and checked if item is string. But I get a very strange output. Tried

I tried the typical sort function and checked if item is string. But I get a very strange output. Tried multiple different approaches.

 var arr = [{section: '12.2.a'},
               {section: '12.2.b.iii'},
               {section: '12.2.c'},
               {section: '12'},
               {section: '12A'},
               {section: '12.3.b'},
               {section: '12.3.c'},
               {section: 'Q2'},
               {section: 'Q32'},
               {section: 'Q6'},
               {section: 'Q5'}]



var arr2 = arr.sort(function(a, b) {
    var nums1 = a.section.split(".");
    var nums2 = b.section.split(".");

    for (var i = 0; i < nums1.length; i++) {
      if (nums2[i]) {
        if (nums1[i] !== nums2[i]) {
          if (isNaN(parseInt(nums1[i])) && isNaN(parseInt(nums2[i]))) {
            return nums1[i].localeCompare(nums2[i]);
          }
          return parseInt(nums1[i]) - parseInt(nums2[i]);   
        }
      } else {
        return 1;
      }
    }
    return -1;
});

Should I use localeCompare or is it possible to without ? Would like the output to be:

[
 {section: '12'},
 {section: '12A'},
 {section: '12.2.a'},
 {section: '12.2.b.iii'},
 {section: '12.2.c'},
 {section: '12.3.b'},
 {section: '12.3.c'},
 {section: 'Q2'},
 {section: 'Q6'},
 {section: 'Q5'}
 {section: 'Q32'}]

Would much appreciate any suggestions

I tried the typical sort function and checked if item is string. But I get a very strange output. Tried multiple different approaches.

 var arr = [{section: '12.2.a'},
               {section: '12.2.b.iii'},
               {section: '12.2.c'},
               {section: '12'},
               {section: '12A'},
               {section: '12.3.b'},
               {section: '12.3.c'},
               {section: 'Q2'},
               {section: 'Q32'},
               {section: 'Q6'},
               {section: 'Q5'}]



var arr2 = arr.sort(function(a, b) {
    var nums1 = a.section.split(".");
    var nums2 = b.section.split(".");

    for (var i = 0; i < nums1.length; i++) {
      if (nums2[i]) {
        if (nums1[i] !== nums2[i]) {
          if (isNaN(parseInt(nums1[i])) && isNaN(parseInt(nums2[i]))) {
            return nums1[i].localeCompare(nums2[i]);
          }
          return parseInt(nums1[i]) - parseInt(nums2[i]);   
        }
      } else {
        return 1;
      }
    }
    return -1;
});

Should I use localeCompare or is it possible to without ? Would like the output to be:

[
 {section: '12'},
 {section: '12A'},
 {section: '12.2.a'},
 {section: '12.2.b.iii'},
 {section: '12.2.c'},
 {section: '12.3.b'},
 {section: '12.3.c'},
 {section: 'Q2'},
 {section: 'Q6'},
 {section: 'Q5'}
 {section: 'Q32'}]

Would much appreciate any suggestions

Share Improve this question asked Oct 20, 2016 at 9:06 ProzrachniyProzrachniy 1518 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I propose a pletely different approach. We're going to modify your strings until they are sortable by localeCompare

Here's how:

// "12" sorts before "2", prefixing to "12" and "02" fixes this
// (length should be bigger than your largest nr)
var makeLength5 = prefixWithZero.bind(null, 5);

// This function generates a string that is sortable by localeCompare
var toSortableString = function(obj) {
  return obj.section
    .replace(/\./g, "z")            // Places `12A` before `12.` but after `12`
    .replace(/\d+/g, makeLength5);  // Makes every number the same length
};

var arr = [{section:"12.2.a"},{section:"12.2.b.iii"},{section:"12.2.c"},{section:"12"},{section:"12A"},{section:"12.3.b"},{section:"12.3.c"},{section:"Q2"},{section:"Q32"},{section:"Q6"},{section:"Q5"}];
var arr2 = arr.sort(function(a, b) {
  return toSortableString(a).localeCompare(toSortableString(b));
});

console.log(JSON.stringify(arr2.map(function(s){ return s.section; }), null, 2));

// Helper methods
function prefixWithZero(length, str) {
  while (str.length < length) {
    str = "0" + str;
  }
  return str;
};

You could split the string and use sorting with map, while paring each element of the one with each element of the other one. if both elements are numbers, take the difference, otherwise return the result of localeCompare.

Bonus: Sort with roman numbers.

function customSort(data, key, order) {

    function isNumber(v) {
        return (+v).toString() === v;
    }

    function isRoman(s) {
        // http://stackoverflow./a/267405/1447675
        return /^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/i.test(s);
    }

    function parseRoman(s) {
        var val = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 };
        return s.toUpperCase().split('').reduce(function (r, a, i, aa) {
            return val[a] < val[aa[i + 1]] ? r - val[a] : r + val[a];
        }, 0);
    }

    var sort = {
            asc: function (a, b) {
                var i = 0,
                    l = Math.min(a.value.length, b.value.length);

                while (i < l && a.value[i] === b.value[i]) {
                    i++;
                }
                if (i === l) {
                    return a.value.length - b.value.length;
                }
                if (isNumber(a.value[i]) && isNumber(b.value[i])) {
                    return a.value[i] - b.value[i];
                }
                if (isRoman(a.value[i]) && isRoman(b.value[i])) {
                    return parseRoman(a.value[i]) - parseRoman(b.value[i]);
                }
                return a.value[i].localeCompare(b.value[i]);
            },
            desc: function (a, b) {
                return sort.asc(b, a);
            }
        },
        mapped = data.map(function (el, i) {
            var string = el[key].replace(/\d(?=[a-z])|[a-z](?=\.)/gi, '$&. .'),
                regex = /(\d+)|([^0-9.]+)/g,
                m,
                parts = [];

            while ((m = regex.exec(string)) !== null) {
                parts.push(m[0]);
            }
            return { index: i, value: parts, o: el, string: string };
        });

    mapped.sort(sort[order] || sort.asc);
    return mapped.map(function (el) {
        return data[el.index];
    });
}

var arr = [{ section: '12.2.a' }, { section: '12.2.b.viii' }, { section: '12.2.b.xi' }, { section: '12.2.b.x' }, { section: '12.2.b.ix' }, { section: '12.2.b.vii' }, { section: '12.2.b.vi' }, { section: '12.2.b.iv' }, { section: '12.2.b.v' }, { section: '12.2.b.ii' }, { section: '12.2.b.iii' }, { section: '12.2.b.i' }, { section: '12.2.b.iii' }, { section: '12.2.c' }, { section: '12' }, { section: '12A' }, { section: '12.3.b' }, { section: '12.3.c' }, { section: 'Q2' }, { section: 'Q32' }, { section: 'Q6' }, { section: 'Q5' }, { section: 'Q.10' }, { section: 'Q.1' }, { section: 'Q.2' }];

console.log('sorted array asc', customSort(arr, 'section'));
console.log('sorted array desc', customSort(arr, 'section', 'desc'));
console.log('original array', arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745639633a4637608.html

相关推荐

  • 聊聊Spring AI Alibaba的ObsidianDocumentReader

    序本文主要研究一下Spring AI Alibaba的ObsidianDocumentReaderObsidianDocumentReadercommunitydocument-readersspring-ai-alibaba-star

    1小时前
    00
  • PackML over OPC UA

    在当今数字化转型的浪潮中,制造业正面临着前所未有的挑战与机遇。如何实现设备之间的高效通信与集成,成为提升生产效率、降低成本的关键。OPC UA(OPC Unified Architecture)与PackML(Packaging Machi

    1小时前
    00
  • 万字图解 Java 并发框架:ForkJoin、CountDownLatch、Semaphore、CyclicBarrier

    本文图多,内容硬核,建议收藏。在第一章节《1.6w 字图解 Java 并发:多线程挑战、线程状态和通信、死锁;AQS、ReentrantLock、Condition 使用和原理》,我们开启了 Java 高并发系列的学习,透彻理解 Java

    1小时前
    00
  • 10个 DeepSeek 神级提示词,建议收藏!

    在当下人工智能飞速发展的时代,DeepSeek 作为一款功能强大的 AI 工具,能够帮助我们实现各种创意和需求。然而,要充分发挥它的潜力,掌握一些巧妙的提示词至关重要。今天,就为大家精心整理了 15 个 DeepSeek 神级提示词,涵盖多

    1小时前
    00
  • HLS最全知识库

    HLS最全知识库副标题-FPGA高层次综合HLS(二)-Vitis HLS知识库高层次综合(High-level Synthesis)简称HLS,指的是将高层次语言描述的逻辑结构,自动转换成低抽象级语言描述的电路模型的过程。对于AMD Xi

    57分钟前
    00
  • 面试官:从三万英尺角度谈一下Ceph架构设计(1)

    把面试官当陪练,在找工作中才会越战越勇大家好我是小义同学,这是大厂面试拆解——项目实战系列的第3篇文章,如果有误,请指正。本文主要解决的一个问题,Ceph为例子 如何描述项目的架构。一句话描述:主要矛盾发生变化10年前的技术和方案,放到10

    52分钟前
    00
  • 如何打造高效AI智能体?

    作者|Barry Zhang, Anthropic地址|出品|码个蛋(ID:codeegg)整理|陈宇明最近看到了 Anthropic 那篇著名的《Building effective agents》作者之一 Barry Zhang 在 2

    51分钟前
    00
  • 国产车载通信测试方案:车规级CAN SIC芯片测试技术解析

    随着智能网联汽车的快速发展,车辆内部电子控制单元(ECU)数量激增,动力总成、高级驾驶辅助系统(ADAS)、车身控制等功能对车载通信网络的稳定性与速率提出了更高要求。传统CAN FD总线在复杂拓扑中面临信号振铃、通信速率受限(实际速率通常低

    43分钟前
    00
  • 最简 Odoo 部署方法:Websoft9 企业应用托管平台

    传统方式部署 Odoo 通常依赖 Docker 技术,主要分为以下步骤:1 . 安装 Docker需在服务器上安装 Docker 引擎,涉及操作系统兼容性检查、依赖包安装、镜像源配置等操作。代码语言:bash复制 # 以 Ubu

    39分钟前
    00
  • ascend pytorch 踩坑.

    在910b上安装pytorch 和 pytorch_npu, 因为后续准备装vllm, 所以torch_npu是特殊的版本.代码语言:shell复制pip install torch==2.5.1 --extra-index pip in

    36分钟前
    00
  • 开源在线考试系统

    看到调问已经开始扩展在线考试的场景,试了一下,发现在线考试的基本能力都已经支持了。主要是考试中的各种计分功能,包括对每道题的选项设置分值计算、考试时间限制等,和官方了解了一下,考试中的其他各项能力也在逐步完善,有需求可以随时

    35分钟前
    00
  • Go 语言 Mock 实践

    Mock 是软件测试中的一项关键技术,尤其在单元测试领域,可谓是“顶梁柱”般的存在,几乎不可或缺。它通过模拟真实对象的行为,使我们能在不依赖外部系统的情况下,专注测试代码的核心逻辑。对于测试开发、自动化测试,乃至性能测试中的某些场景,合理使

    31分钟前
    00
  • 深度学习在DOM解析中的应用:自动识别页面关键内容区块

    爬虫代理摘要本文介绍了如何在爬取东方财富吧()财经新闻时,利用深度学习模型对 DOM 树中的内容区块进行自动识别和过滤,并将新闻标题、时间、正文等关键信息分类存储。文章聚焦爬虫整体性能瓶颈,通过指标对比、优化策略、压测数据及改进结果,展示了

    25分钟前
    10
  • 【Docker项目实战】使用Docker部署IT工具箱Team·IDE

    一、Team·IDE介绍1.1 Team·IDE简介Team IDE 是一款集成多种数据库(如 MySQL、Oracle、金仓、达梦、神通等)与分布式系统组件(如 Redis、Zookeeper、Kafka、Elasticsearch)管理

    17分钟前
    00
  • 拥抱国产化:转转APP的鸿蒙NEXT端开发尝鲜之旅

    本文由转转技术团队赵卫兵分享,原题“鸿蒙新篇章:转转 APP 的 HarmonyOS Next 开发之旅”,下文进行了排版优化和内容修订。1、引言2023 年在华为开发者大会(HDC.Together)上,除了面向消费者的 HarmonyO

    14分钟前
    00
  • 实现一个 MySQL 配置对比脚本需要考虑哪些细节?

    作者:李彬,爱可生 DBA 团队成员,负责项目日常问题处理及公司平台问题排查。爱好有亿点点多,吉他、旅行、打游戏爱可生开源社区出品,原创内容未经授权不得随意使用,转载请联系小编并注明来源。本文约 1500 字,预计阅读需要 3 分钟。引言想

    9分钟前
    00
  • 在VMware虚拟机中安装Windows 7全攻略(避坑指南)

    ⚠️写在前面 最近发现很多开发者在调试老旧系统时都需要用到Windows 7环境&#xff08;特别是银行、医疗等行业的遗留系统&#xff09;&#xff0c;但实体机安装既不现实也不安全。今天就手把手教你在虚拟机

    9分钟前
    00
  • Nat. Mater.

    大家好,今天给大家分享一篇近期发表在Nat. Mater.上的研究进展,题为:De novo design of self-assembling peptides with antimicrobial activity guided

    7分钟前
    00
  • windows新建open ai密钥

    api链接 openai的api需要付费才能使用但好像系统变量不知道为啥用不了打印出来&#xff0c;获取到的是None可以用了

    7分钟前
    00
  • 雨晨 22635.5170 Windows 11 企业版 23H2 轻装版

    文件: 雨晨 22635.5170 Windows 11 企业版 23H2 轻装版 install.esd 大小: 2920270404 字节 修改时间: 2025年4月8日, 星期二, 11 : 04 : 59 MD5: D5F8F0AD

    6分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信