4

I have a result of "ImputacionData", and with a reduces it I group it with an attribute of the object:

this.imputacionesDatas = data;
this.imputacionesAndAusencias = this.imputacionesDatas.reduce(function (r, a) {
        r[a.empleadoId] = r[a.empleadoId] || [];
        r[a.empleadoId].push(a);
        return r;
    }, Object.create(null));

The problem that I do not know how to work with the result, would need to put it in a Map to be able to work with that data on the screen and be able to paint them.

I do not know how to put the result of the "reduce" in something like:

Map <number, Array <ImputacionData >>;
1
  • do you need Map or just an array of arrays? Commented May 9, 2018 at 9:15

2 Answers 2

8

You could take Object.entries for getting keys and values in an array.

this.imputacionesAndAusencias = Object.entries(this.imputacionesDatas.reduce(function (r, a) {
    r[a.empleadoId] = r[a.empleadoId] || [];
    r[a.empleadoId].push(a);
    return r;
}, Object.create(null)));

If you like to get a Map, you could take the map as return value.

this.imputacionesAndAusencias = this.imputacionesDatas.reduce(function (map, object) {
    if (!map.has(object.empleadoId)) {
        return map.set(object.empleadoId, [object]);
    }
    map.get(object.empleadoId).push(object);
    return map;
}, new Map);
Sign up to request clarification or add additional context in comments.

1 Comment

The second example has served me. Thank you.
0

You can set the accumulator's initial value to new Map() and then use the Map methods to set its values.

const input = [{
  empleadoId: 5
}, {
  empleadoId: 5
}, {
  empleadoId: 6
}];
const output = input.reduce((map, item) => {
  const { empleadoId } = item;
  if (map.has(empleadoId)) map.get(empleadoId).push(item);
  else map.set(empleadoId, [item]);
  return map;
}, new Map());
console.log(...output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.