Grouping objects of an array by equivalent dates

Asked

Viewed 79 times

2

Good morning, I have a question where I have an array of objects as follows, for example:

var producao = [{data: '2019-12-19', producao_ok: 10, producao_nok: 20}, {data: '2018-10-01', producao_ok: 5, producao_nok: 1}, {data: '2019-12-19', producao_ok: 100, producao_nok: 2}, {data: '2018-10-01', producao_ok: 100, producao_nok: 10}, {data: '2019-12-19', producao_ok: 10, producao_nok: 20}];

Is there any way, for example with reduce, to sum up the production values and output by grouping dates, bearing in mind that I have no idea of the initial and final dates of the object?

example of expected result after inserting into a new array:

var objetoNovo = [{data: '2019-12-19', producao_ok: 120, producao_nok: 42}, {data: '2018-10-01', producao_ok: 105, producao_nok: 11}];
  • Have you considered using a key/value data structure, for example a map?

1 answer

2


Adapting the answer to the question "how to group by and sum array of Object?" for your example, we can use the function reduce of array to obtain an object with keys according to the field you group and adding the other values. After that it is possible to use the function Object.values to obtain the previously selected values.

const producao = [{
  data: '2019-12-19',
  producao_ok: 10,
  producao_nok: 20
}, {
  data: '2018-10-01',
  producao_ok: 5,
  producao_nok: 1
}, {
  data: '2019-12-19',
  producao_ok: 100,
  producao_nok: 2
}, {
  data: '2018-10-01',
  producao_ok: 100,
  producao_nok: 10
}, {
  data: '2019-12-19',
  producao_ok: 10,
  producao_nok: 20
}];

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

  return acumulador;
};

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

console.log(agrupar(producao));


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

  • 1

    Dude, that’s exactly what it was! It was totally worth it!

Browser other questions tagged

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