Home > Software engineering >  List count array by name attribute dynamics information
List count array by name attribute dynamics information

Time:12-16

I need to show an object with the existing attribute list and showing a number of how many times it appears:

Payload:

[
    [
        "valor"
    ],
    [
        "tipo de entrada",
        "data entrada",
        "valor"
    ],
    [
        "tipo de entrada",
        "data entrada",
        "valor"
    ],
    [
        "tipo de entrada"
    ],
    [
        "tipo de entrada"
    ],
    [
        "tipo de entrada"
    ],
    [
        "valor"
    ],
    [
        "valor"
    ],
    [
        "valor"
    ],
    [
        "valor"
    ],
    [
        "tipo de entrada",
        "data entrada",
        "valor"
    ]
]

Result:

{
    valor: 16,
    tipo_entrada: 9,
    dqta_entrada: 6
}

being that list of attributes dynamically, it can contain other values ​​(value, name, age ...)

CodePudding user response:

You can flatten your array using array#flat() and then using array#reduce count the frequency of each word.

const arr = [ [ "valor" ], [ "tipo de entrada", "data entrada", "valor" ], [ "tipo de entrada", "data entrada", "valor" ], [ "tipo de entrada" ], [ "tipo de entrada" ], [ "tipo de entrada" ], [ "valor" ], [ "valor" ], [ "valor" ], [ "valor" ], [ "tipo de entrada", "data entrada", "valor" ] ],
      result = arr.flat().reduce((r, word) => {
        r[word] = (r[word] ?? 0)   1;
        return r;
      },{});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Here's a one-liner :

var mainData = [ [ "valor" ], [ "tipo de entrada", "data entrada", "valor" ], [ "tipo de entrada", "data entrada", "valor" ], [ "tipo de entrada" ], [ "tipo de entrada" ], [ "tipo de entrada" ], [ "valor" ], [ "valor" ], [ "valor" ], [ "valor" ], [ "tipo de entrada", "data entrada", "valor" ] ]

var resultObj = {};
mainData.map(data => data.forEach(subData => { resultObj[subData] = (Object.keys(resultObj).indexOf(subData) == -1 ? 1 : resultObj[subData]   1) }))
console.log(resultObj)

CodePudding user response:

You can use flat and play around with it.

This code defines and explain a way of resolving your problem:

const result = {};
const initialArray = [['tomato'], ['ketchup', 'potato']];
const strings = initialArray.flat(); // ['tomato', 'ketchup', 'potato']

for (const string of strings) {
  // string is 'tomato' for example
  // result[string] would then be result[tomato]

  if (result[string]) {
    result[string]  = 1; // result.tomato already exists? Add 1 to it
  } else {
    result[string] = 1; // if it does not exists, create it with value 1
  }
}
  • Related