JavaScript:对数组排序

编程入门 行业动态 更新时间:2024-10-20 03:29:28
本文介绍了JavaScript:对数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

未排序的数组[input]:

["> 30 days", "< 7 days", "< 30 days", "< 10 days"];

数组中元素的格式始终类似于:</>X天

The format of an elements in array will always be like : </> X days

要求:

上面提到的数组应按照 大然后(>) 和 小然后符号(<)进行排序,并牢记天数(应减少天数).

Above mentioned array should be sorted as per the greater then (>) and lesser then symbol (<) and also keep the number of days in mind (less number of days should come first).

期望的数组[输出]:

["< 7 days", "< 10 days", "< 30 days", "> 30 days"];

到目前为止已尝试:

我尝试了 Array.sort() 函数,但未获得预期的输出.

I tried Array.sort() function but did not get expected output.

var arr = ["> 30 days", "< 7 days", "< 30 days", "< 10 days"]; var sortedArr = arr.sort(); console.log(sortedArr); // ["< 30 days", "< 10 days", "< 7 days", "> 30 days"]

推荐答案

您可以按数字排序,如果有比较符号可用,则为相同的数值获取两个偏移的增量,以反映比较的顺序.

You could sort by numbers and if a comparison sign is available, then take for the same numerical value the delta of both offsets, which reflects the order of comparison.

var array = ["> 30 days", "< 7 days", "30 days", "< 10 days", "> 10 days", "< 11 days", "42 days", ">= 42 days", "> 42 days", "<= 42 days", "< 42 days"]; array.sort(function (a, b) { function getV(s) { return { value: s.match(/\d+/), offset: { '<': -2, '<=': -1, null: 0, '>=': 1, '>': 2 }[s.match(/[<>]={0,1}(?=\s*\d)/)] }; } var aa = getV(a), bb = getV(b); return aa.value - bb.value || aa.offset - bb.offset; }); console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }

第一个/以前的解决方案

First/former solution

您可以解析字符串,并将其用于对数字应用更正值-然后进行相应的排序.

You could parse the string and use it for applying a correction value to the number - then sort accordingly.

{ '>': 0.1, '<': -0.1, null: 0 }[s.match(/[<>](?=\s*\d)/)] + +s.match(/\d+/)

具有校正值的对象

{ '>': 0.1, '<': -0.1, null: 0 }

使用正则表达式获取符号并将其用作对象的键

get the sign with a regular expression and use it as key for the object

s.match(/[<>](?=\s*\d)/)

然后添加字符串的数字部分

then add the number part of the string

+ +s.match(/\d+/)

var array = ["> 30 days", "< 7 days", "30 days", "< 10 days"]; array.sort(function (a, b) { function getV(s) { return { '>': 0.1, '<': -0.1, null: 0 }[s.match(/[<>](?=\s*\d)/)] + +s.match(/\d+/); } return getV(a) - getV(b); }); console.log(array);

更多推荐

JavaScript:对数组排序

本文发布于:2023-07-29 00:41:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235629.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!