Larger number of occurrences of an element in an array of objects - JavaScript

0

Hello, I have an array of news (objects)

lista: Array<Noticia> = [];

From this array I need to find out the author who most published the news. One news item has:

ID | Title | Tags Author | Content .

My initial idea was:

public totalPublicacoes(){
 var autorM = '';
 var autor = this.lista[0].autor;
 var qtM = 0;
 var qt = 0;
 for(let i=0; i<this.lista.length; i++){       
   if(autor == this.lista[i].autor){
     qt ++;
     if(qt > qtM){
       qtM = qt;
       autorM = this.lista[i].autor;
     }
   }
 }
 console.log(autorM);}

So my initial idea was to get the author of the first array object

check if it was the same as the next author element of the array

If yes I added the qt of times it appeared

if the current qt was greater than the greater number of appearances

I updated the highest appearance value

and kept the name of the author who in most thesis published.

But it's not working, can you help me?

    
asked by anonymous 17.09.2018 / 18:20

2 answers

2

Good morning Gabriel tries this:

seuarraydenoticias.reduce(function (autores, autor) { 
  if (autor.Autor in autores) {
    autores[autor.Autor]++;
  }
  else {
    autores[autor.Autor] = 1;
  }

  return autores;
}, {});

else will return a new array with the author's name and quantity.

I hope to have helped my friend.

    
17.09.2018 / 19:02
0

I was able to solve this problem if someone ever had the same situation:

public maisPublicou() {
const frequency = this.lista
  .map(({ autor }) => autor)
  .reduce((autores, autor) => {
    const count = autores[autor] || 0;
    autores[autor] = count + 1;
    return autores;
  }, {});
var qt = 0;
var autorM = '';
for (var key in frequency) {
  if (frequency[key] > qt) {
    qt = frequency[key];
    autorM = key;
  }
}
return autorM;}
    
17.09.2018 / 20:15