javascript - 如果日期相同,则按日期排序对象数组,然后按字符串值排序

标签 javascript sorting lodash

我有一个对象数组:

arr = [
        {
            name : 'Gary',
            DOB : '01/01/1980',
            importance: 'High'
        },
        {
            name : 'Bill',
            DOB : '01/01/1985',
            importance: 'High'
        },
        {
            name : 'Joe',
            DOB : '01/01/1981',
            importance: 'Medium'
        },
        {
            name : 'Phillip',
            DOB : '01/01/1981',
            importance: 'High'
        },
        {
            name : 'Ed',
            DOB : '01/01/1980',
            importance: 'Low'
        },
        {
            name : 'Nix',
            DOB : '01/01/1980',
            importance: 'High'
        },
        {
            name : 'Pat',
            DOB : '01/01/1980',
            importance: 'Low'
        }
    ]

我按两个字段对这些人进行排序,首先是DOB,如果他们有相同的 DOB,然后是重要性,从低到高,所以低顶部和底部的高点。

我可以很容易地比较它们的日期,但之后我很难按它们的重要性排序?

有人可以提供任何建议吗?

var importanceOrder = ['Low', 'Normal', 'High'];

arr.sort(function(a, b) {
    if(a.dueDate.value != b.dueDate.value){
        return a.dueDate.value < b.dueDate.value ? -1 : 1;
    } else {
    //??
    }
});

最佳答案

您可以采用一个对象作为 重要性 的排序顺序和一个用于获取 ISO 日期的函数。

const getISO = s => s.replace(/(..)\/(..)\/(....)/, '$3-$1-$2');

var array = [{ name: 'Gary', DOB: '01/01/1980', importance: 'High' }, { name: 'Bill', DOB: '01/01/1985', importance: 'High' }, { name: 'Joe', DOB: '01/01/1981', importance: 'Medium' }, { name: 'Phillip', DOB: '01/01/1981', importance: 'High' }, { name: 'Ed', DOB: '01/01/1980', importance: 'Low' }, { name: 'Nix', DOB: '01/01/1980', importance: 'High' }, { name: 'Pat', DOB: '01/01/1980', importance: 'Low' }],
    order = { Low: 1, Normal: 2, High: 3 };


array.sort((a, b) => getISO(a.DOB).localeCompare(getISO(b.DOB)) || order[a.importance] - order[b.importance]);

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

关于javascript - 如果日期相同,则按日期排序对象数组,然后按字符串值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50290933/

相关文章:

javascript - 删除对象成员并且不留下未定义的最佳方法是什么

javascript - lodash find() 的流式注解

arrays - 如何使用 Lo-Dash 对数组进行降序排序?

javascript - 从 td (Javascript) 获取元素?

javascript - 设置全局时区

excel - 对具有特定条件的excel表进行排序(vba)

perl - 按 mmyy 排序(月和年)

javascript - 使用 13 个 OR 比较运算符编写 if 语句的简写方法?

c# - asp.net 中运行时的确认对话框

python - Numpy.argsort - 看不出有什么问题