1

Example

[
    { language: 'JavaScript' },{ language: 'JavaScript' },{ language: 'TypeScript' },
] 

SHOULD BE CONVERTED TO =

[
{ language: 'JavaScript', count: 2 },
{ language: 'C++', count: 1 },
{ language: 'TypeScript', count: 1 }
]

The idea is to count the frequency of each unique key in an array of objects and then instead of making the result look like

{ key1: 2, key2: 1, key3: 7 } 

The result should be an array of objects so that it can be map over and get rendered in React.JS or something like that.

[ { key1: 2 }, { key2: 1 }, { key3: 7 } ]
  • Where does `C++` come from? Also please post the code you've written in an effort to solve this yourself so that we can help you to debug it. – Rory McCrossan Oct 06 '22 at 14:39
  • Does this answer your question? [Count duplicates within an Array of Objects](https://stackoverflow.com/questions/10541068/count-duplicates-within-an-array-of-objects) – Heretic Monkey Oct 07 '22 at 00:41
  • My question is differing from you have given link in terms of input & output. Given sample link isn't solve my criteria. Given solutions mostly except fix input & counted output is differ from required too. @HereticMonkey – Jesicca Austina Oct 07 '22 at 01:22

1 Answers1

0

You can use the below code to get exactly what you wanted. It applies to all inputs. You have to pass the array & property name on which the count is calculated.

const superAob = (data, victim) => {

    const obj = {};
  
    data.forEach((data) => {
        if(data.hasOwnProperty(victim)){
            if(obj[data[victim]]){
                obj[data[victim]]++;
            }
            else{
                obj[data[victim]] = 1;
            }
        }
    })
  
    let superArrayOfObjects = [];
  
    for (const key in obj) {
        superArrayOfObjects = [...superArrayOfObjects, { victim: key, count: obj[key]}];
    }
  
    return superArrayOfObjects;
}

let aob = 
[
    { framework: 'React.JS', website: 'Paypal' },
    { framework: 'React.JS', website: 'Tesla' },
    { framework: 'Angular', website: 'Google' },
    { framework: 'Vue.JS', website: 'Vue' },
    { framework: 'JavaScript', website: 'inblack67' },
]

console.log(superAob(aob, 'framework'));

aob = 
[
    { language: 'JavaScript' },{ language: 'JavaScript' },{ language: 'TypeScript' },
]

console.log(superAob(aob, 'language'));
Ashok Dhaduk
  • 165
  • 2
  • 8