explain complicated reduce use case Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of explain complicated reduce use case without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the following array:

[0:{
boat: "Laura"
date: "2022-05-14"
doy: 133
end: "22:00:00"
fname: "David"
lname: "Cross"
skipperid: 217
spots: 5
start: "09:00:00"
type: "RES"},
1:{
boat: "Avrora"
date: "2022-05-14"
doy: 133
end: "13:00:00"
fname: "Bob"
lname: "Smith"
skipperid: 1
spots: 3
start: "10:00:00"
type: "SAIL"}]

I apply the following to turn it into an object of arrays where the keys to each object is the skipperid.

daySails = daySails.reduce((b, a) => ({        
           ...b,
           [a.skipperid]: a
           }), {});

could someone explain how this works?

Answer

I would write that differently to avoid creating a new object on each iteration, and also to make it less “complicated”:

daySails = daySails.reduce((b, a) => {
  b[a.skipperid] = a;
  return b;
}, {});

Each iteration adds a new element to the result object, with the “skipperid” as its key. In each call to the => callback function, b is the object being built step-by-step (initialized with the {} in the .reduce() call), and a is an element of the source array (the original daySails). Thus each source element is added to the built-up result element by it’s skipperid.

Note that if two entries in the original have the same skipperid, you’ll end up with only one. The usual way to deal with that, if it’s a problem you face, is to turn the entries into arrays instead of just single objects:

daySails = daySails.reduce((b, a) => {
  // Check if the "skipperid" is present already
  if (!b[a.skipperid])
    b[a.skipperid] = []; // nope, so create new array 
  b[a.skipperid].push(a); // add element
  return b;
}, {});
We are here to answer your question about explain complicated reduce use case - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji