Count Array data

1

I need a way to reduce a array and unify and count the matches in a% new matriz , this is the data:

Reduce a array of a API , convert them to matriz and count the names of the countries and leave only the countries without repeating and the number of times they appear repeated

datos = [{"PaisExportador": "CHINA","fila": 1}, 
         {"PaisExportador": "URUGUAY","fila": 2},
         {"PaisExportador": "HONG KONG","fila": 3}, 
         {"PaisExportador": "CHINA","fila": 4}
        ];

matriz = [[{"nombre": "CHINA","cant": 2}],
          [{"nombre": "URUGUAY","cant": 1}],
          [{"nombre": "HONG KONG","cant": 1}]
         ]
    
asked by Gdaimon 19.11.2016 в 17:47
source

1 answer

2

To count the countries you can do a Loop. Then use an object as a map to accumulate the values.

var datos = [{"PaisExportador": "CHINA","fila": 1}, 
         {"PaisExportador": "URUGUAY","fila": 2},
         {"PaisExportador": "HONG KONG","fila": 3}, 
         {"PaisExportador": "CHINA","fila": 4}
        ];

var matriz = {};

datos.forEach(function(registro) { 
  var pais = registro["PaisExportador"];
  matriz[pais] = matriz[pais] ? (matriz[pais] + 1) : 1;
});

console.log(matriz);

Then if you need that specific format that you put in the question, you can use map to translate from one format to the other, like in this example:

var datos = [{"PaisExportador": "CHINA","fila": 1}, 
         {"PaisExportador": "URUGUAY","fila": 2},
         {"PaisExportador": "HONG KONG","fila": 3}, 
         {"PaisExportador": "CHINA","fila": 4}
        ];

var matriz = {};

datos.forEach(function(registro) { 
  var pais = registro["PaisExportador"];
  matriz[pais] = matriz[pais] ? (matriz[pais] + 1) : 1;
});

// luego puedes usar la primera matriz, para crear el arreglo con tu formato necesitado.
matriz = Object.keys(matriz).map(function(pais) {
   return { nombre: pais, cant: matriz[pais] };
});
console.log(matriz);
    
answered by 19.11.2016 / 18:08
source