flatt

mail@pastecode.io avatar
unknown
javascript
2 years ago
943 B
3
Indexable
Never
function flatten(main_array){
  //base case 
  if(main_array.length === 0){
    return [];
  }
  //result array (every function call will have its own result array)
  let result_array = [];

  //get first element in array, 
  let first_element = main_array[0];
  
  //if first element is an array, then call flatten on it again
  if(Array.isArray(first_element)){
    let result_from_flatten = flatten(first_element);
    //reassign result with combined result from recursive flatten with new array.
    result_array = result_array.concat(result_from_flatten);
  }
  //else push element to new array.
  else{
    result_array.push(first_element);
  }

  //now continue flattening the rest of the elements of the original array that isn't the first_element, and combine w/ result_array.
  let flatten_next = flatten(main_array.slice(1));
  let final_result = result_array.concat(flatten_next);
  return final_result;
}