The returned data may be several months old. How to calculate the lowest price for each month? The following is the data structure:
Thank you~
var data = [ { date: "2017-04-20", price: 1170 }, { date: "2017-04-21", price: 1450 }, { date: "2017-04-22", price: 960 }, { date: "2017-04-25", price: 2300 }, { date: "2017-05-21", price: 1203 }, { date: "2017-05-22", price: 1206 }, { date: "2017-03-20", price: 658 } ]; var monthMap = {}; data.forEach(function (n) { var month = n.date.substring(0, 7); if (!monthMap[month] || monthMap[month] > n.price) { monthMap[month] = n.price; } }); // {2017-04: 960, 2017-05: 1203, 2017-03: 658} console.log(monthMap);
var arr = [ { date: '2017-04-20', price: 1170 }, { date: '2017-04-21', price: 1450 }, { date: '2017-04-22', price: 940 } ]; var newArr = arr.sort(function (a, b) { return a.price > b.price; }); console.log(newArr[0].price); // -> 940
First sort the array by price from small to large, Then get the first content of the array which is the one with the smallest price.
First sort the array by price from small to large,
Then get the first content of the array which is the one with the smallest price.