0

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
]

1 Answers1

0

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; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
  • 1
    Thanks for the answer, but this question has already been asked before https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements – evolutionxbox Jan 28 '21 at 17:02