Reputation: 2689
I have an array of objects which contain dates. I want to count the number of times a date occurs in a month. For example if there are dates like 2019-01-14, 2019-01-15, 2019-01-16 then the count for January should be 3. I want to do this for each month but not too sure how to approach it without making the code too obtuse.
var jan = 0;
this.btcDebts.map((item) => {
let date = new Date(item.date);
if (date.toString().includes('Jan')){
jan++;
}
})
console.log(jan);
This works, but for 11 other months it will just become repetitive. Is there a simpler way?
Upvotes: 1
Views: 119
Reputation: 214969
No need to convert these string fields to Dates, just group by the first 7 chars:
let countBy = (a, fn) => a.map(fn).reduce(
(m, k) => m.set(k, 1 + (m.get(k) || 0)),
new Map);
//
items = [
{date: '2019-01-14'},
{date: '2019-02-14'},
{date: '2019-03-14'},
{date: '2019-01-14'},
{date: '2019-02-14'},
{date: '2019-03-14'},
{date: '2019-04-14'},
{date: '2019-05-14'},
{date: '2019-01-14'},
{date: '2019-03-14'},
]
counts = countBy(items, item => item.date.slice(0, 7));
for (let [mon, cnt] of counts)
console.log(mon, cnt)
Upvotes: 2
Reputation: 4275
Maybe try using getMonth() to get month of a date. (Also Remember it returns an integer not the string). Try the code below if the item.date can be also in another format.
var jan = 0;
var MONTHS = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11};
this.btcDebts.map((item) => {
let date = new Date(item.date);
if (date.getMonth() === MONTHS["JAN"]){
jan++;
}
})
console.log(jan);
@RobG mentioned the best solution for your case since there's no need to create a new Date Object to parse strings. Try the code below:-
var jan = 0;
var MONTHS = {JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6, JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12};
this.btcDebts.map((item) => {
let month = parseInt(item.date.split("-")[1]); // Only works for this format like 2019-01-16
if (month === MONTHS["JAN"]){
jan++;
}
})
console.log(jan);
Hope this helps
Upvotes: 1
Reputation: 906
You can use getMonth()
method of Date
class. It returns months from 0-11
. Documentation Link
var days_in_each_month = [];
this.btcDebts.map((item) => {
let date = new Date(item.date);
days_in_each_months[date. getMonth()]++; //month starts from zero. Zero means January.
});
console.log(days_in_each_months);
Upvotes: 1