Hi I am trying to convert array of strings into an array of objects as follows
let array = [a,a,a,b,b,c,c,d,c,e,a,a]
//which transforms into
object = [
{
value:a,
count:5
},
{
value:b,
count:2
},
//etcetera
]
Hi I am trying to convert array of strings into an array of objects as follows
let array = [a,a,a,b,b,c,c,d,c,e,a,a]
//which transforms into
object = [
{
value:a,
count:5
},
{
value:b,
count:2
},
//etcetera
]
You can use a combination of .reduce()
, .map()
and Object.entries()
to get the desired output:
let data = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'c', 'e', 'a', 'a'];
let result = Object.entries(
data.reduce((r, c) => (r[c] = (r[c] || 0) + 1, r), {})
).map(([value, count]) => ({ value, count }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }