gpt4 book ai didi

javascript - JQuery - 获取关联数组的最小和最大日期

转载 作者:行者123 更新时间:2023-11-30 14:17:15 25 4
gpt4 key购买 nike

我有这个关联数组:

[{"start_date":"2018-11-20", "end_date":"2019-01-20", name:"NO Name"},
{"start_date":"2018-10-10", "end_date":"2019-02-14", name:"Name No"},
{"start_date":"2019-02-15", "end_date":"2019-03-01", name:"No Name No"}]

我想获得的值是 minimun 开始日期 2018-10-10maximum 结束日期 2019-03-01。我怎样才能得到它?

我尝试过的:

data = '[{"start_date":"2018-11-20", "end_date":"2019-01-20", name:"NO Name"},{"start_date":"2018-10-10", "end_date":"2019-02-14", name:"Name No"},{"start_date":"2019-02-15", "end_date":"2019-03-01", name:"No Name No"}]';

var end_date = new Date();
var start_date = new Date();


for (var i=0; i<data.length; i++) {
if (data[i].end_date > end_date) {
end_date = data[i].end_date
}

if (data[i].start_date > start_date) {
start_date = data[i].start_date;
}
}

console.log(end_date);
console.log(start_date);

最佳答案

您可以通过 String.localeComparestart_date 排序然后获取结果数组的第一个和最后一个元素:

const data = [{ "start_date": "2018-11-20", "end_date": "2019-01-20", name: "NO Name" }, { "start_date": "2018-10-10", "end_date": "2019-02-14", name: "Name No" }, { "start_date": "2019-02-15", "end_date": "2019-03-01", name: "No Name No" } ]

const result = data.sort((a,b) => a.start_date.localeCompare(b.start_date))
console.log(result[0], result[result.length-1])
// Just the dates
console.log(result[0].start_date, result[result.length-1].start_date)

关于javascript - JQuery - 获取关联数组的最小和最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com