How to find an object, inside which is the smallest and largest price

 "2018-02": { "2018-02-09": { "price": 13025 }, "2018-02-15": { "price": 12499 } }, "2018-04": { "2018-04-01": { "price": 15990 } } 

The result should be an object:

 { "max": { "price": 15990, "month": "2018-04", "date": "2018-04-01" }, "min": { "price": 12499, "month": "2018-02", "date": "2018-02-15" } } 

Initially I planned to sort the keys of the days of each month first, and then the months themselves, but an algorithmic porridge was brewing in my head and something I wanted to write such a whopper. Is there a simpler way?

  • so that the maximum and minimum find sorting is not needed. - teran 8:55 pm

1 answer 1

to find the minimum and maximum values, sorting is not needed, just look at all the keys once

 var data = { "2018-02": { "2018-02-09": { "price": 13025 }, "2018-02-15": { "price": 12499 } }, "2018-04": { "2018-04-01": { "price": 15990 } } }; var min = {price : 999999999999 }, max = {price: 0}; for( m in data ){ for(d in data[m]){ let obj = data[m][d]; if(obj.price < min.price){ min = { month: m, date: d, price: obj.price }; } if(obj.price > max.price){ max = { month: m, date: d, price: obj.price }; } } } console.log(min, max); 

  • Cool! Thank you, I will take this method into service. - JamesJGoodwin