Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

explain complicated reduce use case

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}, {});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading