Skip to content
Advertisement

how to find average prices from one array by crossing it to last 30 days from other array? javascript

I have these 2 arrays , one contains the time period, the second one contains the prices for each period.

how can I output the average price for the last 30 days, 60 days, etc…?

time[
'2021-01-14', '2021-02-08', '2021-02-16',
'2021-02-16', '2021-02-17', '2021-02-22',
'2021-02-26', '2021-02-28', '2021-04-07',
'2021-04-25', '2021-04-26', '2021-05-10',
'2021-05-11', '2021-05-13', '2021-05-15',
'2021-05-16', '2021-05-24', '2021-06-09',
'2021-06-14', '2021-06-14', '2021-06-17',
'2021-06-19', '2021-06-20', '2021-07-15',
'2021-07-17', '2021-07-17', '2021-07-19',
'2021-07-19', '2021-08-02'
]
prices[
 79999, 69999, 76641, 76506, 79999,
 69999, 64999, 69999, 79999, 72500,
 69999, 72500, 77449, 77433, 77684,
 79999, 69999, 79999, 69999,    -1,
 69999,    -1, 69999, 74999, 69999,
 74999, 69999, 74999, 64999
]

Advertisement

Answer

Here I combine the two arrays using map() and make the time into a Data object. I create a Date object and reduce it by 30 days. I filter the combined array using filter() and calculate the sum of the prices using reduce().

var time = [
'2021-01-14', '2021-02-08', '2021-02-16',
'2021-02-16', '2021-02-17', '2021-02-22',
'2021-02-26', '2021-02-28', '2021-04-07',
'2021-04-25', '2021-04-26', '2021-05-10',
'2021-05-11', '2021-05-13', '2021-05-15',
'2021-05-16', '2021-05-24', '2021-06-09',
'2021-06-14', '2021-06-14', '2021-06-17',
'2021-06-19', '2021-06-20', '2021-07-15',
'2021-07-17', '2021-07-17', '2021-07-19',
'2021-07-19', '2021-08-02'
];
var prices = [
 79999, 69999, 76641, 76506, 79999,
 69999, 64999, 69999, 79999, 72500,
 69999, 72500, 77449, 77433, 77684,
 79999, 69999, 79999, 69999,    -1,
 69999,    -1, 69999, 74999, 69999,
 74999, 69999, 74999, 64999
];

var combined = time.map((d,i) => {return {date: new Date(d), price: prices[i]}});

//var d = new Date();
// for the purpose of this fixed set of date/price this code will have a fixed "now"-date instead of a future date:
var d = new Date('2021-08-04');
d.setDate(d.getDate()-30);

var filtered = combined.filter(item => item.date.getTime() > d.getTime());

console.log('Should return 6 objects when d = 2021-08-04:', filtered.length);

var priceSum = filtered.reduce((accumulator, item) => {return accumulator + item.price}, 0);

console.log('Should return 429994:', priceSum);

You can adjust the time range by defining another date object from a fixed date, like:

var d = new Date('2021-08-01');
console.log(d);
d.setDate(d.getDate()-60);
console.log(d);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement