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

时间:2018-11-20 01:47:26

标签: javascript jquery arrays json

我有这个关联数组:

[{"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);

1 个答案:

答案 0 :(得分:2)

您可以通过String.localeCompare通过start_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)