Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Arbitrarily nested array
- let arr = [[[[1,2],[[3,3],4],5,6]],7];
- // Final array that would contain the flattened elements
- let flattenedArray = [];
- /*
- * @function flatten
- *
- * @args element element to be flattened or passed back to recursion
- *
- * @description if the element is an array pass each of elements to this function.
- * When the element is not an array , push this element to the flattened array
- *
- * @output flattenedArray contains the flattened form of the initial arbitrarily sized array
- */
- function flatten(element) {
- if (element.constructor === Array) {
- for (let idx = 0; idx < element.length; idx++) {
- flatten(element[idx]);
- }
- } else {
- flattenedArray.push(element);
- }
- }
- // Call the function with the main array as the argument
- flatten(arr);
- // Print the final flattened array (output)
- console.log(flattenedArray);
Add Comment
Please, Sign In to add comment