-1

i have an array of objects that i want to count by cs parameters and fine how many tt in each cs?

const object : [
0:{cs:56 ,tt:'aaa'},
1:{cs:23 , tt:'bbb'},
2:{cs:56 ,tt: 'ppp'},
3:{cs:56 ,tt: 'sss'},
4:{cs:23 , tt:'rrr'}]
enter code here

// and final result that I except is

// finallObject ={cs:23,count:2},{cs:56 ,count:3}

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
sepideh bb
  • 45
  • 2
  • 7
  • 1
    Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). Code that you have worked on to solve the problem should include a [mcve], and be included in your question. – Andy May 17 '22 at 06:04
  • https://stackoverflow.com/questions/52711740/group-array-and-get-count – cmgchess May 17 '22 at 06:05
  • Does this answer your question? [Count identical objects by 2 properties in an array and introduce a count property](https://stackoverflow.com/questions/66171440/count-identical-objects-by-2-properties-in-an-array-and-introduce-a-count-proper) – Rickard Elimää May 17 '22 at 06:13
  • const groupBy = (keys) => (array) => array.reduce((objectsByKeyValue, obj) => { const value = keys.map((key) => obj[key]).join("-"); objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj); return objectsByKeyValue; }, {}); const object = [ {cs:56 ,tt:'aaa'}, {cs:23 , tt:'bbb'}, {cs:56 ,tt: 'ppp'}, {cs:56 ,tt: 'sss'}, {cs:23 , tt:'rrr'}]; const groupByBrandAndYear = groupBy(["cs"]); for (let [groupName, values] of Object.entries(groupByBrandAndYear(object))) { console.log(`cs:${groupName},count:${values.length}`); } – Vinay May 17 '22 at 06:23

1 Answers1

1

Please refer to this.

const object = [
            {cs:56 ,tt:'aaa'},
            {cs:23 , tt:'bbb'},
            {cs:56 ,tt: 'ppp'},
            {cs:56 ,tt: 'sss'},
            {cs:23 , tt:'rrr'}
            ]
    
            var aa = new Set(object.map(x => {
                return x.cs
            }))
    
            let newObj = [];
    
            aa.forEach(element => {
                let cnt = object.filter(x => x.cs == element).length;
                newObj.push({cs: element, count: cnt});
            });
    
            console.log(newObj);
Nishan Dhungana
  • 831
  • 3
  • 11
  • 30