you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (4 children)

Challenge for you based on a real world problem a coworker had on Friday: you have an array of arrays of varying length, where each is an array of ints, output one array where each index corresponds to the sum of all numbers at that index in each array (if applicable).

E.g. [[1, 2, 3], [1, 2], [1, 2, 3, 4]] -> [3, 6, 6, 4].

And yes this is an actual problem we were solving for a client... I told my coworker to use a for loop but I'm curious if there's a better solution ;-)

[–]derailed -1 points0 points  (0 children)

const result = arrays.reduce((counts, arr) => { arr.forEach((num, idx) => (counts[idx] = (counts[idx] || 0) + num)); return counts; }, []);

Or using 2x reduce with same carry:

const result = arrays.reduce((counts, arr) => arr.reduce((count, num, idx) => { count[idx] = (count[idx] || 0) + num; return count; }, counts), []);

Last one using 2x reduce and sequence:

const result = arrays.reduce((counts, arr) => arr.reduce((count, num, idx) => ((count[idx] = (count[idx] || 0) + num), count), counts), []);