Function that Flattens and Push elements to given array
Last active
October 14, 2016 07:17
-
-
Save ananthhh/1d4c8f7c0ab32a3b782d8fd54ce544f4 to your computer and use it in GitHub Desktop.
Flatten and Push the elements to given array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Push elements to given array. | |
| * If any provided element is array, flattens them before pushing. | |
| * How it works: | |
| * flattenAndPush([], [1, 2, 3], 4, 5) | |
| * -> flattenAndPush(flattenAndPush([], 1, 2, 3), 4, 5) | |
| * -> flattenAndPush([1, 2, 3], 4, 5) | |
| * -> [1, 2, 3, 4, 5] | |
| * | |
| * @param {Array} array Array to push elements | |
| * @param elements It collects all remaining parameters in array. | |
| * @return {Array} Returns array with elements pushed to original array. | |
| */ | |
| function flattenAndPush(array, ...elements) { | |
| return elements.reduce((curr, next) => { | |
| if(next instanceof Array) return flattenAndPush(curr, ...next); | |
| else { | |
| curr.push(next); | |
| return curr; | |
| } | |
| }, array); | |
| } | |
| const testArray = [[1,2,[3, [2, 'abc']]],4]; | |
| console.log(JSON.stringify(flattenAndPush([], ...testArray))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment