I am trying to take in an array of names (with duplicates) and output a array of objects.
Input: single array
const arr = ['M', 'M', 'M', 'S', 'S', 'S', 'R', 'C', 'S', 'S', 'S']
Output: array of objects
[
{
name: 'M'
duplicates: 3
},
{
name: 'S'
duplicates: 6
}...
]
I have tried this solution, but this is giving me the name of each array item for the key name. That is not what I want.
This is my current code:
const result = arr.reduce((acc, curr) => {
acc[curr] ??
(acc[curr] = {
[curr]: 0,
})
acc[curr][curr]
return acc
}, [])
console.log(result)
/*output:
[
C: {C: 1}
M: {M: 3}
R: {R: 1}
S: {S: 6}
]
*/
CodePudding user response:
Index the accumulator by the element, increment counts for matching keys, strip out the index (with Object.values) at the end...
const arr = ['M', 'M', 'M', 'S', 'S', 'S', 'R', 'C', 'S', 'S', 'S'];
let result = Object.values(arr.reduce((acc, el) => {
if (!acc.hasOwnProperty(el)) acc[el] = { name: el, duplicates: 0 };
acc[el].duplicates ;
return acc;
}, {}));
console.log(result)