Akash Agrawal
Akash Agrawal

Reputation: 2299

Get Unique Key-Value count as an object

I've got the following response from the server:

enter image description here

I want to get the unique key with the occurrence count. In the following format:

0:{"name":"physics 1","count":2}
1:{"name":"chem 1","count":6}

I've already checked How to count the number of occurrences of each item in an array? but that is not I want.

Upvotes: 1

Views: 1995

Answers (3)

HimanshuArora9419
HimanshuArora9419

Reputation: 737

use this function this uses map and filter

 t.reduce((f,l)=>{
    var k=f.filter(elem=>elem.section_name==l.section_name);
    if(k.length==1) k[0].count++;
    else f.push({section_name:l.section_name,count:1})
    return f;
},[] )

you can check this against this to verify

var t=[{section_name:"Physics"},{section_name:"Physics"},{section_name:"Chemistry"},{section_name:"Chemistry"},{section_name:"Physics"}]

Upvotes: 0

Shane
Shane

Reputation: 3199

Here is an es6 solution.

const data = [{
    id: 0,
    name: 'physics 1',
    questionId: 1,
    questionNr: 1
}, {
    name: 'physics 1',
}, {
    name: 'chem 1',
}, {
    name: 'chem 1',
}, {
    name: 'chem 2',
}];

const grouped = data.reduce((groups, cur) => {
    const key = cur.name;

    groups[key] = (groups[key] || 0) + 1;

    return groups;
}, {});

const result = Object.keys(grouped).map(key => ({name: key, count: grouped[key]}));

console.log(result);

Upvotes: 5

dferenc
dferenc

Reputation: 8126

You could do it this way:

var source = [
    {'section_name': 'test1'},
    {'section_name': 'test2'},
    {'section_name': 'test1'},
];

var temp = {};
for (var i = source.length - 1; i >= 0; i--) {
    var key = source[i].section_name;
    if (!temp[key]) {
        temp[key] = 0;
    } 

    temp[key] += 1;
}

var keys = Object.keys(temp);
var result = [];
for (var i = keys.length - 1; i >= 0; i--) {
    var key = keys[i];

    result.push({"name":key,"count":temp[key]});
}

console.log(result);

Upvotes: 1

Related Questions