如何在javascript中根据时间戳对3个排序的数组进行排序



给定3个排序的对象数组,其中每个对象都有一个时间戳键,我如何在Javascript中将它们合并为一个单独的排序数组,其中最终数组是根据时间戳排序的?

// merge these messages, flights and hotels arrays into one array and sort them 
// messages, flights and hotels are already sorted 
const messages = [{"timestamp": "2019-06-28", "message": "messageVal"}, {"timestamp": "2019-06-29", "message": "messageVal"}];
const flights = [{"timestamp": "2019-08-19", "flight": "flightVal"}, {"timestamp": "2019-08-28", "flight": "flightVal"}];
const hotels = [{"timestamp": "2019-11-20", "hotel": "hotelVal"}];

您可以将所有这些组合在一个数组中,将其展开并排序

const messages = [
{ timestamp: "2019-06-28", message: "messageVal" },
{ timestamp: "2019-06-29", message: "messageVal" },
]
const flights = [
{ timestamp: "2019-08-19", flight: "flightVal" },
{ timestamp: "2019-08-28", flight: "flightVal" },
]
const hotels = [{ timestamp: "2019-11-20", hotel: "hotelVal" }]
const res = [messages, flights, hotels]
.flat()
.sort((a, b) => b.timestamp - a.timestamp)
console.log(res)

您可以将时间戳属性转换为Date,使用flat((合并数组,然后排序。

我做了一个简单的功能,可以帮助你,它允许上升和下降。

let array1 = [{"timestamp": "2019-06-30", "message": "1"}, {"timestamp": "2019-06-29", "message": "2"}];
let array2 = [{"timestamp": "2019-06-27", "message": "3"}, {"timestamp": "2019-06-26", "message": "4"}];
function sortArray(input, isDescending = false){
return input.flat().sort((x1, x2) => isDescending ? new Date(x2.timestamp) - new Date(x1.timestamp) : new Date(x1.timestamp) - new Date(x2.timestamp));
}
console.log(sortArray([array1, array2])); //Ascending
console.log(sortArray([array1, array2], true)); //Descending

相关内容

  • 没有找到相关文章

最新更新