Gab
Gab

Reputation: 2276

Using javascript/lodash to group identical values for a specific key and count them and return results to an array

I have a collection of objects from which I use lodash's _.map function to get all the corresponding values for a specific key:

[{
    "id": 1,
    "alarm_type": "danger",
    "data": "Dapibus ac facilisis in facilisilitumas el perfertum"
}, {
    "id": 2,
    "alarm_type": "danger",
    "data": "Cras sit amet nibh libero"
}, {
    "id": 3,
    "alarm_type": "warning",
    "data": "Porta ac consectetur ac"
}, {
    "id": 4,
    "alarm_type": "info",
    "data": "Vestibulum at eros porta ac consectetur ac"
}, {
    "id": 5,
    "alarm_type": "success",
    "data": "Morbi leo risus"
}, {
    "id": 6,
    "alarm_type": "default",
    "data": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}, {
    "id": 7,
    "alarm_type": "danger",
    "data": "Cras sit amet nibh libero"
}, {
}, {
    "id": 8,
    "alarm_type": "default",
    "data": "Dolor sit amet, consectetur adipiscing."
}, {
    "id": 9,
    "alarm_type": "default",
    "data": "Dolor sit amet, consectetur adipiscing elit."
}]

The javascript functions:

var alarmsQueue = alarms.getAlarms();

alarmsQueue.then(function(result) {

    var alarmsTypes = _.map(result, 'alarm_type');

    console.log(alarmsTypes);

});

The result is the following array:

["danger", "danger", "warning", "info", "success", "default", "danger", "default", "default"]

And I would like to obtain the following object from the previous:

{"danger": 3, "warning": 1, "info": 1, "success": 1, "default": 3}

What would be the best way to proceed?

Upvotes: 4

Views: 1405

Answers (3)

maioman
maioman

Reputation: 18762

You can't have ["danger": 3, "warning": 1, "info": 1, "success": 1, "default": 3],

but you could group the key-values in an object and have:

[{"danger": 3}, {"warning": 1}, ....]

or make a unique object with key-value pairs like:

 {"danger": 3, "warning": 1, ....}

here's the solution to the second scenario using reduce method:

var alarmsTypes = _.reduce(result, function (ac,v) {

     if ( ac[v.alarm_type] ) {
       ac[v.alarm_type] ++;
     }else{
      ac[v.alarm_type] = 1;
     };
   return ac
   },{});

fiddle

Upvotes: 1

Shashank
Shashank

Reputation: 13869

It's a one-liner using _.countBy.

_.countBy(alarmsTypes)

Upvotes: 3

Arg0n
Arg0n

Reputation: 8423

Look at this JSFiddle

JavaScript

var alarmTypes = ["danger", "danger", "warning", "info", "success", "default", "danger", "default", "default"];

var alarmTypeCount = {};

for(var i = 0; i < alarmTypes.length; i++){
    var alarmType = alarmTypes[i];
    if(alarmTypeCount[alarmType]) {
        alarmTypeCount[alarmType]++;
    } else {
        alarmTypeCount[alarmType] = 1;
    }
}

console.log(JSON.stringify(alarmTypeCount)); // {"danger":3,"warning":1,"info":1,"success":1,"default":3}

Upvotes: 1

Related Questions