Group array with javascript

Asked

Viewed 91 times

-1

I have a backend application in Node that returns the following array:

let res= [
           {
                codigo: '0341',
                codigo_1: '0320',
                visao: '14',
                total: 24,
                data: '201502'
            },
            {
                codigo:'0341',
                codigo_1:'0320',
                visao:'14',
                total:25,
                data: '201504'
            },
            {
                codigo:'0321',
                codigo_1:'0320',
                visao:'14',
                total:31,
                data: '201506'
            },
            {
                codigo:'0341',
                codigo_1:'0320',
                visao:'14',
                total:55,
                data: '201502'
            },
        ]

The date attribute is composed by year/month, I can not change as it comes from the base so

I need the return grouped initially by date and then by code summing the totals, taking the following return:

 [
      {
          data: '201502'
          codigo: '0341'
          total: 79
      },
      {
          data: '201506'
          codigo: '0321'
          total: 31
      },
      {
          data: '201504'
          codigo: '0320'
          total: 25
      }
  ]

I have tried some forms, but without success. Follow:

const resultadosAgrupados = res.reduce(function (valorAcumulador, valorArray) {
            if (!valorAcumulador[valorArray.data]) {
                valorAcumulador[valorArray.data] = { ...valorArray };
                return valorAcumulador;
            }
            valorAcumulador[valorArray.data].total += valorArray.total;
            return valorAcumulador
        }, [])

And also using uniqBy:

let teste = _.uniqBy(res, 'data')

Thank you.

1 answer

3


Adapting this answer to the question Grouping objects of an array by equivalent dates for your need we have the following functions:

let dados = [{
    codigo: '0341',
    codigo_1: '0320',
    visao: '14',
    total: 24,
    data: '201502'
  },
  {
    codigo: '0341',
    codigo_1: '0320',
    visao: '14',
    total: 25,
    data: '201504'
  },
  {
    codigo: '0321',
    codigo_1: '0320',
    visao: '14',
    total: 31,
    data: '201506'
  },
  {
    codigo: '0341',
    codigo_1: '0320',
    visao: '14',
    total: 55,
    data: '201502'
  },
];

const reduzir = (acumulador, { data, codigo_1, total }) => {
  // Se ainda não existir o registro no agrupamento
  if (!acumulador[data]) {
    acumulador[data] = {
      data,
      codigo: codigo_1,
      total: total,
    };
  } else {
    acumulador[data].total += total;
  }

  return acumulador;
};

const agrupar = (conjunto) => {
  return Object.values(conjunto.reduce(reduzir, {}));
};

console.log(agrupar(dados));


Object.values

The method Object.values() returns an array with the properties values of a given object, in the same order provided by for...in loop (the difference being that the for-in loop also enumerates the properties in the prototypes string).


reduce

The method reduce() performs a function reducer (provided by you) for each member of the array, resulting in a single return value.

Example:

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

Browser other questions tagged

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