Selecting information that repeats many times

Asked

Viewed 33 times

-1

I wonder if there is any way to select information that repeats many times. Example: I have an object array:

array = [{fruta: maçã}, {fruta: maçã}, {fruta: banana}]

Note that the apple fruit repeats twice and the banana only 1.

I needed a variable to receive the 'Apple' because it is the one that appears most.

I’m doing like this: this.variavel = array[0].fruta but this way I’m only getting the first and not the one that appears more.

Any suggestions?

1 answer

2


You can create an object that with the count of each fruit using Array.reduce() and passing an object as accumulator. There at each step you increment the key containing the fruit found inside the reduce.

After you have the object with the counts you can use the Array.reduce() again to return only the largest of the objects entries(Object.()).

let frutas = [
  {fruta: "maçã"}, 
  {fruta: "maçã"}, 
  {fruta: "banana"},
  {fruta: "melancia"},
  {fruta: "maçã"}, 
  {fruta: "banana"}
];

// counter carrega um objeto no formato {nome_fruta: num_ocorrencias}
let counter = frutas.reduce((acc, {fruta}) => {
  acc[fruta] = (acc[fruta] || 0) + 1;
  return acc;
}, {});
console.log(counter)

// recebe nas variáveis o nome da fruta com mais ocorrências, com o número de ocorrências
 let [nome_fruta, num_ocorrencias] = Object.entries(counter).reduce((acc, entry) => entry[1] > acc[1] ? entry : acc);

console.log(`A fruta "${nome_fruta}" apareceu ${num_ocorrencias} vezes na listagem de frutas.`);


In that reply explain a little better about the functioning of Array.reduce() of the accumulator parameter.

Browser other questions tagged

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