Greater amount of appearances of an element in an object array - Javascript

Asked

Viewed 62 times

0

Hello, I have a news array(objects)

lista: Array<Noticia> = [];

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

ID | Title | Tags | Author | Contents.

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);}

With this my initial idea was to catch the author of the first object of the array

check if it was equal to the next author element of the array

if yes I was adding the Qt of times it appeared

if the current Qt was greater than the larger amount of apparitions

i updated the value of the highest appearance

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

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

2 answers

2


Good morning Gabriel tries like 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 I helped friend.

  • Our worked out! thank you very much! just a doubt, the type of these authors is obj right? so I will have to break-Ló to be able to compare the right values?

  • I’m actually trying to separate these values now so I can compare and say who published, but it’s hard since I don’t know what the name of the value says about the publication count..

0

People I managed to solve, in case someone one day goes through 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;}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.