3

I want to display the amount of users based on which month they are created. I got the following data as example:

[ 
  { 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 display them like this:

may: 4
june: 2
august: 3

How can I do that?

Praveen
  • 8,945
  • 4
  • 31
  • 49
ST80
  • 3,565
  • 16
  • 64
  • 124
  • What have you tried so far? ...need pure javascript? ...or external libraries, such as JQuery, can be used? Look at https://stackoverflow.com/questions/1960473/unique-values-in-an-array for inspiration. – MarcM May 29 '17 at 10:23
  • @MarcM I've just tried to loop through the data array but I'm kinda stuck since I have no clue how to achieve this. Pure javascript would be favorized. :-) I just need an idea how to... – ST80 May 29 '17 at 10:26

4 Answers4

4

You can use reduce() and return object as 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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
0

I think this will give you the idea:

const usersCreatedInMay = users.filter(u => u.created == 'may')

usersCreatedInMay will return null or an array. Just look at the length of it to learn how many users created in may.

usersCreatedInMay.length

You can loop through all months and calculate how many users created in each month.

muratgozel
  • 2,333
  • 27
  • 31
0

You could try something that goes in this direction, code may not work since it is not tested.

function extract(month, data) {
       return let result = data.filter((res)=>{
        return res.created === month;
    })
Amiga500
  • 5,874
  • 10
  • 64
  • 117
0

This is a 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 the working fiddle - https://jsfiddle.net/sajalsuraj/7nychnd2/

Cheers!!

sajalsuraj
  • 922
  • 15
  • 29