简体   繁体   English

如何根据 javascript 中的时间戳对 3 个已排序的 arrays 进行排序

[英]how to sort 3 sorted arrays based on timestamps in javascript

Given 3 sorted arrays of objects, where each object has a timestamp key, how would I merge them into a single sorted array in Javascript, where the final array is sorted based on timestamp?给定 3 个排序的 arrays 对象,其中每个 object 都有一个时间戳键,我如何将它们合并到 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"}];

You could combine these all in one array, flatten it and sort您可以将所有这些组合在一个数组中,将其展平并排序

 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)

You can convert the timestamp property to Date, merge the arrays using flat() and then sort.您可以将时间戳属性转换为日期,使用 flat() 合并 arrays 然后排序。

I did a simple function which can help you, it allows ascending and descending.我做了一个简单的 function 可以帮助你,它允许上升和下降。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM