Scroll through an array of dates to pick up the amount of monthly records from the last 12 months

Asked

Viewed 146 times

1

I have an array with dates, each date means a new record in the users table, in this case, a new user account created. I need to go through this array to get the amount of accounts created over the last 12 months.

var arr = [“2018-02-19”, “2018-02-19”, “2018-02-19”, “2018-02-19”, “2018-02-19”, “2018-02-19”, “2018-02-19”, “2018-02-19”, “2018-03-23”, “2018-03-23”, “2019-06-12”, “2019-06-12”, “2019-06-15”, “2019-06-15”, “2019-06-15”, “2019-06-15”];  

Result should be:

02/2018 -> 8 contas criadas

03/2018 -> 2 contas criadas

06/2019 -> 6 contas criadas

My code:

function setArray(array) {

var thisDate = array[0];
var count = 0;
var qtd = [];
var datas = [];

for (var i = 0; i < array.length; i++) {

    if (array[i] == thisDate) {
        count++;
    }
    if (array[i] != thisDate) {
        datas = thisDate;
        qtd = count;
        count = 0;
    }
    thisDate = array[i];
}

console.log(datas);
console.log(qtd);

}

setArray(arr);

Note: The array is dynamic. So it always changes. After all, I want to get the monthly amount of records from the last 12 months.

2 answers

2


Why not create a map or an object to associate dates with occurrences?

var arr = ['2018-02-19', '2018-02-19', '2018-02-19', '2018-02-19', '2018-02-19', '2018-02-19', '2018-02-19', '2018-02-19', '2018-03-23', '2018-03-23', '2019-06-12', '2019-06-12', '2019-06-15', '2019-06-15', '2019-06-15', '2019-06-15'];  
var ocorrencias = arr.reduce((acc, data) => {
    // Converto a data no formato MM/AA
    const mesAno = `${data.slice(5, 7)}/${data.slice(0, 4)}`;
    // Incremento no objeto, já considerando a possibilidade da propriedade não existir
    acc[mesAno] = (acc[mesAno] || 0) + 1;
    // Retorno o objeto para o método reduce
    return acc;
}, {});

console.log(ocorrencias);

Now just iterate over the object using a for..in, or convert it to an array of pairs with Object.entries(ocorrencias).

0

var arr = ["2018-02-19", "2018-02-19", "2018-02-19", "2018-02-19", "2018-02-19", "2018-02-19", "2018-02-19", "2018-02-19", "2018-03-23", "2018-03-23", "2019-06-12", "2019-06-12", "2019-06-15", "2019-06-15", "2019-06-15", "2019-06-15"];
var contagens={};
arr.forEach(function(v,i){
    if(contagens[v.slice(5,7)]!=undefined){
         contagens[v.slice(5,7)]=contagens[v.slice(5,7)]+1;
    }else{
         contagens[v.slice(5,7)]=1;
    }
})
console.log(contagens);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.