Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Let's set up some example arrays with arbitrarily
- nested arrays within
- */
- const array1 = ['a', 'b', ['c', 'd']]
- const array2 = ['a', ['b', 'c'], 'd']
- const array3 = ['a', ['b', ['c', 'd']], 'e']
- /*
- We'll use the prototype reduce() function.
- It takes a callback and an initial value.
- It will establish an accumulator with the initial value.
- It will then execute the callback on each item in the array.
- We will make a function that will take an array,
- use the reduce() method to run a callback that appends
- each value to the accumulator. If the value is another
- array, it will call itself recursively against that array.
- This will allow it to flatten an infinite number of nested
- arrays into a single flat array
- */
- const flatten = (array) => array.reduce(
- (acc, val) => acc.concat(
- Array.isArray(val) ? flatten(val) : val
- ), []
- )
- /*
- Let's test it out on our arrays
- */
- const flatArray1 = flatten(array1);
- const flatArray2 = flatten(array2);
- const flatArray3 = flatten(array3);
- /*
- And log our results to the console
- */
- console.log(flatArray1); // logs '["a", "b", "c", "d"]'
- console.log(flatArray2); // logs '["a", "b", "c", "d"]'
- console.log(flatArray3); // logs '["a", "b", "c", "d", "e"]'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement