如何在多个键上对ImmutableJS List对象排序? [英] How can I sort an ImmutableJS List object on multiple keys?

查看:126
本文介绍了如何在多个键上对ImmutableJS List对象排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含startend日期字段的工作历史对象列表.我需要按start排序,然后按end排序.如果在我使用背靠背sort()函数时工作历史对象之间的日期重叠,则该订单可能已关闭.我需要一种通过多个键对ImmutableJS列表进行排序的方法,其中仅当第一个键值相等时才处理第二个排序键.我本以为ImmutableJS将有一种更简单的方式来处理这种类型的排序.这是我想出的,但这对我来说太可怕了(使用momentJS进行日期比较):

I have a list of work history objects that have start and end date fields. I need to sort by start and then by end. If the dates overlap between work history objects when I use back-to-back sort() functions, the order can potentially be off. I need a way to sort an ImmutableJS List by multiple keys where the second sort key is only processed when first key values are equal. I would have assumed that ImmutableJS would have a simpler way to handle this type of sorting. Here is what I came up with, but this feels horrible to me (using momentJS for date comparison):

    const sortedWorkHistory = workHistory.sort((b, a) => {
        const aTo = moment(a.get('to') === null ? undefined : a.get('to'));
        const bTo = moment(b.get('to') === null ? undefined : b.get('to'));

        if (aTo.isBefore(bTo)) {
            return -1;
        }

        if (bTo.isBefore(aTo)) {
            return 1;
        }

        return 0;
    })
    .sort((b, a) => {
        const aTo = moment(a.get('to') === null ? undefined : a.get('to'));
        const bTo = moment(b.get('to') === null ? undefined : b.get('to'));

        if (aTo === bTo) {
            const aFrom = moment(a.get('from'));
            const bFrom = moment(b.get('from'));

            if (aFrom.isBefore(bFrom)) {
                return -1;
            }

            if (bFrom.isBefore(aFrom)) {
                return 1;
            }

            return 0;
        }
    });

推荐答案

aTo === bTo永远不会与您定义它的方式相同.您正在将引用与始终不同的对象进行比较.您将需要使用moments .isSame方法.您可以尝试通过以下方式进行验证:

aTo === bTo is never going to be equal the way you are defining it. You're comparing references to objects which are always different. You'll need to use moments .isSame method. You can verify that by trying this:

const a = moment().startOf('day');
const b = moment().startOf('day');
console.log(a === b);  // false
console.log(a.isSame(b));  // true

这就是我要做的:

// Helper function to create moments
function parseMoment(date) {
    return moment(date === null ? undefined : date);
}

const sortedWorkHistory = workHistory
    .sort((a, b) => parseMoment(a.get('to')).diff(parseMoment(b.get('to'))))
    .sort((a, b) => {
        if(parseMoment(a.get('to')).isSame(parseMoment(b.get('to')))) {
            return parseMoment(a.get('from')).diff(parseMoment(b.get('from')))
        }
        return 0;
    });

这篇关于如何在多个键上对ImmutableJS List对象排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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