Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const flatten = (array) => {
- // Concat nested arrays recursively
- const f = (arr, acc) => {
- if(arr.length > 0) {
- const first = arr[0];
- if(Array.isArray(first)) {
- // Item is an array, start new call
- acc = acc.concat(f(first, []));
- } else {
- // Add iem to accumulator
- acc.push(first);
- }
- // Continue with next item
- return f(arr.slice(1), acc);
- } else {
- // Nothing to do, return accumulator
- return acc;
- }
- };
- // Start
- return f(array, []);
- };
- // console.log('Result:',flatten([1, [2, 3], 4, [5, [6, [7, 8]]], 9, 0]));
- module.exports = flatten;
Add Comment
Please, Sign In to add comment