Trying to find the best way to create an array of objects where I get only the Maximum and Minimum values for twice a day (before 12:00pm noon and after 12:00pm noon). The result should still return in order of time.
The best way I know to do it is:
- First filter the data based on the day (I'm using moment.js)
- Then filter the day into 2 different arrays: beforeNoon[], afterNoon[]
- Then get the Maximum value of the arrays using reduce
- Then get the Minimum value of the arrays using reduce
- Combine the results into 1 array, and sort by time ascending
I was hoping there would be a much easier way to do this... let me know if you have any suggestions. Thanks in advance for any suggestions!
const data = [
{"t":"2020-05-27 03:42","v":"2.151"},
{"t":"2020-05-27 08:48","v":"3.125"},
{"t":"2020-05-27 11:54","v":"4.106"},
{"t":"2020-05-27 18:00","v":"5.094"},
{"t":"2020-05-27 21:06","v":"4.088"},
{"t":"2020-05-27 23:12","v":"3.090"},
{"t":"2020-05-28 00:18","v":"2.098"},
{"t":"2020-05-28 03:24","v":"1.114"},
{"t":"2020-05-28 08:30","v":"2.136"},
{"t":"2020-05-28 12:36","v":"3.166"},
{"t":"2020-05-28 17:42","v":"4.202"},
{"t":"2020-05-28 22:48","v":"5.245"},
];
// STEP 1:
// Filter data to only return specific date "2020-05-27"
const today = data.filter( d => moment(d.t).format('YYYY-MM-DD') === '2020-05-27');
console.log('TODAY= ' + JSON.stringify(today));
// STEP 2:
// Divide today's data into half
const todayBeforeNoon = today.filter(d => moment(d.t).format('HH') <= '11');
const todayAfterNoon = today.filter(d => moment(d.t).format('HH') > '11');
console.log('TODAY BEFORE NOON= ' + JSON.stringify(todayBeforeNoon));
console.log('TODAY AFTER NOON= ' + JSON.stringify(todayAfterNoon));
// STEP 3:
// Get the max value per half day
const beforeNoonMax = todayBeforeNoon.reduce( (a, b) => { return (a.v > b.v) ? a : b}, 0);
const afterNoonMax = todayAfterNoon.reduce( (a, b) => { return (a.v > b.v) ? a : b}, 0);
console.log('MAX BEFORE NOON= ' + JSON.stringify(beforeNoonMax));
console.log('MAX AFTER NOON= ' + JSON.stringify(afterNoonMax));
// STEP 4:
// Get the min value per half day
const beforeNoonMin = todayBeforeNoon.reduce( (a, b) => { return (a.v < b.v) ? a : b}, 0);
const afterNoonMin = todayAfterNoon.reduce( (a, b) => { return (a.v < b.v) ? a : b}, 0);
console.log('MIN BEFORE NOON= ' + JSON.stringify(beforeNoonMin));
console.log('MIN AFTER NOON= ' + JSON.stringify(afterNoonMin));
// STEP 5:
// Combine the results into 1 array, and sort by time?
// HELP? SUGGESTIONS?
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>