How to count objects more cleanly?

Asked

Viewed 97 times

-1

I would like to know how to count the same objects and return an array with the respective amounts of times it appeared.

I’m using several "for" to do this, and I don’t know how to do it with "map, reduce"

For example:

Entree:

array1 = [
  {nome: joao, sobrenome: silva},
  {nome: claudio, sobrenome: silva},
  {nome: jose, sobrenome: oliveira},
  {nome: joao, sobrenome: costa},
  {nome: joao, sobrenome: silva}
]

Exit:

array2 = [
  {nome: joao, sobrenome: silva, quantidade: 2},
  {nome: joao, sobrenome: costa, quantidade: 1},
  {nome: claudio, sobrenome: silva, quantidade: 1},
  {nome: jose, sobrenome: oliveira, quantidade: 1}
]
  • The simplest way to do it is by using for. There’s no reason to create additional complexity using reduce. You can see something like this reply. Moreover, the notation of his example is wrong.

1 answer

1


By steps, conceptually, it could be:

  • creates a parallel array to include counters
  • traverses each object to test and add to the counter

In practice this could be done:

const array1 = [
  {nome: 'joao', sobrenome: 'silva'},
  {nome: 'claudio', sobrenome: 'silva'},
  {nome: 'jose', sobrenome: 'oliveira'},
  {nome: 'joao', sobrenome: 'costa'},
  {nome: 'joao', sobrenome: 'silva'}
];

const contador = array1.reduce((obj, el) => {
  const signature = JSON.stringify(el);
  if (!obj[signature]){
    obj[signature] = {...el, quantidade: 0};
  }
  obj[signature].quantidade ++;
  return obj;
}, {});
const contados = Object.values(contador);

console.log(contados);

  • Sergio, Voce can help me understand what is happening within the "if"?

Browser other questions tagged

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