0

I am trying to get the number of times each string item occurs in an array and print it out using a Map. I am basically reading in the data from firebase functions, but for now, I am using an array to test the code to get the occurrences of each item. I tried the following code from here, but it does not work and I am not sure why:

<script>
var appVersion= ["5012", "5021", "5012", "5011", "5012", "5021"];

var count = new Map();

appVersion.forEach(version=> count.set(count.get(version) + 1));

function show(versions) {
         document.write(versions);
         document.write("<br>");
      }
    count.forEach(show);
</script>

Any help or advice will be highly appreciated.

4 Answers4

1

Maybe this helps

var appVersion= ["5012", "5021", "5012", "5011", "5012", "5021"];

let counter = {}
for (version of appVersion){
    counter[version] = 1 + (counter[version] || 0)
}

console.log(counter);
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
  • This does help, but I strictly need to use a map for my case unfortunately. Any advice on that end would be really helpful? –  Jul 12 '20 at 19:16
0

probably you want to this

as discussed in the comments if you want the final object to be in this format :{ '5011': 1, '5012': 3, '5021': 2 } you could use reduce

var appVersion= ["5012", "5021", "5012", "5011", "5012", "5021"];


map=new Map
appVersion.forEach(o=>{
   count=map.get(o)||0
    map.set(o,count+1)
})
r=[...map].reduce((acc,curr)=>{
  if (acc.length==0) {acc.push({[curr[0]]:curr[1]})}
  else  {acc[0][curr[0]]=curr[1]}
 return acc
},[])

console.log(r)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
0

Using map:

let contador = {};
appVersion.map(x => contador[x] = 1 + (contador[x] || 0));
console.log(contador);
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

See below

var appVersion= ["5012", "5021", "5012", "5011", "5012", "5021"];

var count = new Map();

appVersion.map( (version) => count.get( version) != undefined ? count.set( version, count.get( version) + 1 ) : count.set( version, 1 ) );

console.log( [...count].sort() );
Gerard
  • 15,418
  • 5
  • 30
  • 52
  • how would I represent the output as something like this: something like this: `{ "5011": 1, "5012": 3, "5021": 2 }` –  Jul 12 '20 at 19:30
  • I see, but the output is still in this format: [ `[ "5011", 1 ], [ "5012", 3 ], [ "5021", 2 ] ]` Whereas I am looking for something like this: `{ "5011": 1, "5012": 3, "5021": 2 }` Sorry for the bad format, comments don't allow me to format it properly –  Jul 12 '20 at 19:34
  • I apologise for the trouble, I tried it myself, but I am getting stuck with the format –  Jul 12 '20 at 19:41