search

Home  >  Q&A  >  body text

javascript - JS data processing, how to calculate the lowest monthly value?

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~

淡淡烟草味淡淡烟草味2833 days ago628

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:40:25

    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);
    

    reply
    0
  • 阿神

    阿神2017-05-19 10:40:25

    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.

    reply
    0
  • Cancelreply