Count how many equal names there are within a JSON and display in Nodejs screen

Asked

Viewed 844 times

0

I have a json that has names of equal people, and I need to count how many names are repeated and give a total sum. I did it one way, but he’s counting the number of characters in the name and not counting the total number of equal names.

{
      "candidates": [    

        {

          "CLIENT_ID": "Dread Pirate Alannah Company",
          "VALUE": 0,
          "LOST_VALUE": 45,
        },
        {

          "CLIENT_ID": "Dread Pirate Alannah Company",  
          "VALUE": 56.25,
          "LOST_VALUE": 0,
        },
        {

          "CLIENT_ID": "Dread Pirate Alannah Company",
          "VALUE": 45,
          "LOST_VALUE": 0,
        },
        {

          "CLIENT_ID": "Wis Company",
          "VALUE": 45,
          "LOST_VALUE": 0,
        }
      ]
    }

Code that I applied

function allRejected(arr){

    var contador = 0;

    if (arr !== undefined){
        for (var item = 0; item < arr.length; item++){
            if (item !== undefined && arr.indexOf(item)){
                contador ++;
            }
        }
    }
    return contador;
}
  • @Why Andrémartins? What’s wrong with him?

  • I was wrong were 2 in the morning rsrs @Costamilam

2 answers

0


There are several problems in your code, I can’t imagine how it came to this, it seems that mixed several ways to do something similar to what you want

I will put a commented solution to understand

function allRejected(arr) {
  //O contador passa a ser um objeto, onde as chaves serão os nomes e os valores serão o número de repetições
  var contador = {};

  //Removi o "!== undefined" para ele verificar se for diferente de null, false ou 0 também
  if (arr) {
    //Percorre o array com a sintaxe "for of"
    for (var item of arr) {
      //Remoção do "!== undefined" novamente, 
      if (item) {
        //Se o contador não possui uma propriedade com o nome igual a item.CLIENT_ID
        if (contador[item.CLIENT_ID] === undefined) {
          //Cria essa propriedade e atribui o tamanho do array filtrado
          //A função filter irá iterar sobre o array e remover o que o callback retornar false sem alterar o array original
          contador[item.CLIENT_ID] = arr.filter(function(item2) {
            //Se CLIENT_ID do loop "for of" for igual ao do filter retorna true, se não, false
            return item.CLIENT_ID === item2.CLIENT_ID
            //A função filter retornará um array com os itens que tiverem o mesmo CLIENT_ID, para saber quantos são, basta acessar o tamanho (length)
          }).length;
        }
      }
    }
  }

  //Retorna o objeto que contém o número de repetições 
  return contador;
}

//Mostra no console o resultado
console.log(allRejected([
  {
    "CLIENT_ID": "Dread Pirate Alannah Company",
    "VALUE": 0,
    "LOST_VALUE": 45,
  },
  {
    "CLIENT_ID": "Dread Pirate Alannah Company",
    "VALUE": 56.25,
    "LOST_VALUE": 0,
  },
  {
    "CLIENT_ID": "Dread Pirate Alannah Company",
    "VALUE": 45,
    "LOST_VALUE": 0,
  },
  {
    "CLIENT_ID": "Wis Company",
    "VALUE": 45,
    "LOST_VALUE": 0,
  }
]))

  • I did some tests with this piece of code that you gave me and I saw that there are two problems (at least I believe they are), one is that the for of does not accept the . length and filter informs me that arr.filter is not a function ( arr.filter is not a Function )

  • The first was my typing error, the second may be that you have passed the object instead of the property candidates which is an array. I edited the answer with an executable

0

const data = {
  "candidates": [    

    {

      "CLIENT_ID": "Dread Pirate Alannah Company",
      "VALUE": 0,
      "LOST_VALUE": 45,
    },
    {

      "CLIENT_ID": "Dread Pirate Alannah Company",  
      "VALUE": 56.25,
      "LOST_VALUE": 0,
    },
    {

      "CLIENT_ID": "Dread Pirate Alannah Company",
      "VALUE": 45,
      "LOST_VALUE": 0,
    },
    {

      "CLIENT_ID": "Wis Company",
      "VALUE": 45,
      "LOST_VALUE": 0,
    }
  ]
}

Take all the names:

const names = data.candidates.map( candidate => candidate.CLIENT_ID )

Filters the repeated names:

const uniqNames = names.filter((name, index, self) => self.indexOf(name) === index)

Go through all the names and see how many names there are:

let result = [];
uniqNames.forEach( uName => {
    names.forEach( name => {
        if (name == uName) {
            result[uName] = (result[uName] > 0 ? result[uName] : 0)  + 1
        }
    })
})

// result: [Dread Pirate Alannah Company: 3, Wis Company: 1]

You can also create an implementation that you remove from the array names the records that have already been counted.

Browser other questions tagged

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