Skip to content

Instantly share code, notes, and snippets.

@bredfern
Created September 14, 2019 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bredfern/a63e5e6e8564991d22b50124965f5614 to your computer and use it in GitHub Desktop.
Save bredfern/a63e5e6e8564991d22b50124965f5614 to your computer and use it in GitHub Desktop.
Flatting lists with reduce
While not every language uses the "reduce" keyword you find the concept of reduction in different languages that implement functional code features so in c# its called using the Aggregate keyword but the concept is similar.
So what is a reduction and how does it help us flatten multidimensional lists in general?
You basically get to call a function on every item in an array however you get some special tools to keep track of this array so you have an accumulator that is like a bag where all the values drop in after each array is iterated, you have a current value placeholder an index which tells you which item you're on in the array and you have the ability to set an initial value to send to the first callback call.
Here's an example of how reduce is used with a complex array to flatten it into a simple array:
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
In this example you can see that we pass in every element in the original array, if the element is a type of array then we call the function recursively if its a singe value its concated ito the list.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment