I am interested in understanding what is happening inside this algorithm. Let's consider the following dataset:
const data = [
{
emp_code: "a001",
company_code: "company_a",
name: "abx",
details: [],
details_dtypes: []
},
{
emp_code: "b002",
company_code: "company_b",
name: "xbz ",
details: [],
details_dtypes: []
},
{
emp_code: "a002",
company_code: "company_a",
name: "xbz ",
details: [],
details_dtypes: []
},
{
emp_code: "b003",
company_code: "company_b",
name: "xbz ",
details: [],
details_dtypes: []
}
];
Now, if I wanted to condense this data to an object {}
, where each key is a unique company_code
and its corresponding value is an array []
of emp_codes
for that company, I could do something like:
let result = data.reduce((r, c) => {
r[c.company_code] = [...(r[c.company_code] || []), c.emp_code];
return r;
}, {});
In the above, we explicitly return the final object, which seems very clear.
Now, I've recently discovered that you can shorten this up with some syntactic sugar like so:
let result = data.reduce(
(r, c) =>
(r[c.company_code] = [...(r[c.company_code] || []), c.emp_code]) && r,
{}
);
The results are identical, but I'm not sure how that's possible. My understanding of reduce()
is that there is an inner-loop that iterates over each item and allows you to apply certain logic to formulate your final result.
I see that they're using a &&
operator. My hypothesis is that the logic between the parenthesis ()
executes like a traditional reduce()
method and when complete, we simply return the result, hence && r
.
But something about that just seems wrong. Is the inner-loop still happening? If it is how are they able to isolate it like that without simply executing the condition after the first iteration, thus by returning r
. Are they returning r
for each iteration of the loop?
Here's a sandbox that shows both algorithms working: https://codesandbox.io/s/hooks-with-reduce-nested-data-goee1. Many thanks to your contributions :)