问题描述
我有一个包含start
和end
日期字段的工作历史对象列表.我需要按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对象排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!