Skip to content

Instantly share code, notes, and snippets.

@ananthhh
Last active October 14, 2016 07:17
Show Gist options
  • Select an option

  • Save ananthhh/1d4c8f7c0ab32a3b782d8fd54ce544f4 to your computer and use it in GitHub Desktop.

Select an option

Save ananthhh/1d4c8f7c0ab32a3b782d8fd54ce544f4 to your computer and use it in GitHub Desktop.
Flatten and Push the elements to given array
/**
* 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