Javascript how to display the number of users depending on what month they are created
I want to display the number of users based on what month they are created. As an example, I gave the following data:
[
{ name: 'user1', created: 'may' },
{ name: 'user2', created: 'may' },
{ name: 'user3', created: 'may' },
{ name: 'user4', created: 'may' },
{ name: 'user5', created: 'june' },
{ name: 'user6', created: 'june' },
{ name: 'user7', created: 'august' },
{ name: 'user8', created: 'august' },
{ name: 'user9', created: 'august' }
]
what i want to achieve is to show them like this:
may: 4
june: 2
august: 3
How can i do this?
source to share
You can use reduce()
and return an object as a result.
var data = [{"name":"user1","created":"may"},{"name":"user2","created":"may"},{"name":"user3","created":"may"},{"name":"user4","created":"may"},{"name":"user5","created":"june"},{"name":"user6","created":"june"},{"name":"user7","created":"august"},{"name":"user8","created":"august"},{"name":"user9","created":"august"}]
var result = data.reduce(function(r, e) {
return r[e.created] = (r[e.created] || 0) + 1, r
}, {})
console.log(result)
source to share
I think this will give you an idea:
const usersCreatedInMay = users.filter(u => u.created == 'may')
usersCreatedInMay
will return null
or array
. Just view its length to see how many users have been created in the bank.
usersCreatedInMay.length
You can view all months and calculate how many users are created in each month.
source to share
This is pure javascript code you can use: -
var monthWithUsercount = {};
for (var i = 0; i < a.length; i++) {
var num = a[i];
monthWithUsercount[num.created] = monthWithUsercount[num.created] ? monthWithUsercount[num.created]+1 : 1;
}
//Here "a" is the array consisting months and users.
console.log(monthWithUsercount);
Here is a working fiddle - https://jsfiddle.net/sajalsuraj/7nychnd2/
Hooray!!
source to share