JavaScript:对数组排序 [英] JavaScript : Sorting an array

查看:76
本文介绍了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:对数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆