Reputation: 63
I have this associative array:
[{"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"}]
The value I wanted to get is the minimun
start date which is 2018-10-10
and the maximum
end date which is 2019-03-01
. How can I get that?
What Ive Tried:
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);
Upvotes: 1
Views: 260
Reputation: 18515
You can just sort by start_date
via String.localeCompare
and then get the fist and last element of the resulting array:
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)
Upvotes: 2