我有这个关联数组:
[{"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-10
和maximum
的结束日期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);
答案 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)