Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Flattens an array, e.g. [[1,2,[3]],4] -> [1,2,3,4]
- Using Array.prototype.reduce() as a functional alternative to a for loop and
- relying on recursion to handle nesting.
- For those unfamiliar, the first argument to reduce() is a function to run for
- every item of the array and the second argument is the initial value that we
- want to add to, which will eventually be our result. In this case we start with
- an empty array and add each nested item to it.
- */
- const flatten = nestedArray =>
- nestedArray.reduce((flatArray, currentValue) => {
- if (Array.isArray(currentValue))
- flatArray.push(...flatten(currentValue));
- else
- flatArray.push(currentValue);
- return flatArray;
- },
- []);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement