The outcome of the returned function is an array with unspecified results obtained from the original

I've been working on creating a simple function in ES5 to deep flatten an array. The current implementation appears to work, but it seems suboptimal because the res results array is defined outside of the actual flatten function.

    var arr = [1, 2, [3], [4, [5, [6, 7, 8, 9, 10, 11]]]]
      , res = [];
    function flatten(item){
      if (Array.isArray(item)) {
       item.forEach(el => {
         return flatten(el, res);
       });
      }else {
        res.push(item);
      }
    }
    
    flatten(arr);
    console.log(res); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Trying something similar with an IIFE seems promising:

function flatten(item){
  var res = [];
  return (function(ress){
    if (Array.isArray(item)) {
     item.forEach(el => {
       return flatten(el);
     });
    }else {
      res.push(item);
    }
  })(res);
}

However, I have not quite achieved the desired outcome as res remains undefined here. Ideally, the final line of the function should return res so that the function can be utilized like var f = flatten(arr).

NB

*This question does not focus solely on how to deep flatten an array, as there are numerous solutions available for that. My main interest lies in finding a way to keep the results variable inside the parent function in this particular case. *

Answer №1

Embed the recursive function within the primary function to encapsulate the res variable inside it.

var list = [1, 2, [3],
  [4, [5, [6, 7, 8, 9, 10, 11]]]
];

function compress(item) {
  var result = [];

  function compress_recursive(item) {
    if (Array.isArray(item)) {
      item.forEach(el => {
        compress_recursive(el);
      });
    } else {
      result.push(item);
    }
  }
  
  compress_recursive(item);
  return result;
}

var res = compress(list);
console.log(res); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Answer №2

Here's an alternative method using the Array.prototype.reduce in JavaScript.

var arr = [1, 2, [3], [4, [5, [6, 7, 8, 9, 10, 11]]];

var res = arr.reduce(function flatten(a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    return b.reduce(flatten, a);
  } else {
    return a.concat(b);
  }
}, []);

console.log(res);
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}

Answer №3

In my view, taking an iterative approach is more effective than using recursion.

// This function flattens all arguments into a new single-level array.
const flatten = (...queue) => {
    const result = [];

    while (queue.length > 0) {
        const item = queue.shift();

        if (Array.isArray(item)) {
            let i = item.length;
            // If the array has elements, add them to the beginning of the queue to preserve their order.
            while (i--) {
                queue.unshift(item[i]);
            }
        }
        else {
            result.push(item);
        }
    }

    return result;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add a numbered alert to a button using HTML5, jQuery, PHP, or JavaScript?

I have a button on my HTML page that directs users to a page containing email features. I'm looking for a way to show users the number of unread messages they have before they click on the button to view them. I want this to be a subtle alert without ...

Update the value of a scope variable directly within a controller. Subsequently making a function call

Hey there, I just want to start by saying sorry in case this question has already been asked or if it seems silly. I'm pretty new to AngularJS and have managed to overcome CORS errors, set up login via Parse, and even created an API for my app using ...

Issue with Element.update() method malfunctioning on IE browser is causing concern

Utilizing the Element.update() method from the prototype: [ ... ] var link_1 = new Element('a').update( '<' ); var link_2 = new Element('a').update( '<<' ); [ ... ] Encountering a unique issue only in IE: ...

The postback event continues to trigger even if the OnClientClick function returns false

Is there a way to prevent Button1_Click from firing after a Jquery function returns false in my code snippet below? <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- ...

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

Ways to activate jQuery validation when submitting a form instead of triggering it on blur

I am currently utilizing the Jquery Validation plugin to validate form fields upon submission. However, I have encountered an issue where incorrect email format triggers a validation message when moving to the next input field. This behavior is undesirable ...

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...

Revalidating doesn't seem to work as expected in Next JS

Reviewing my code on the development server function Home(props) { console.log("Hello") return ( <ul> {props.user.map((user) => ( <li key={user.id}>{user.email}</li> ))} </ul> ) } expo ...

Table sorting feature with checkboxes has disappeared from view

This segment of code includes HTML for a table along with JavaScript functionality. When a checkbox is clicked, another table will be displayed: <form class="filter"> <input type="checkbox" id="checkboxID" class="unchecked"> EG <input type= ...

Ways to verify an array object and an array

Primary list: [VariationSpecificsSet] => SimpleXMLElement Object ( [NameValueList] => Array ( [0] => SimpleXMLElement Object ( ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Leveraging jQuery within Node.js

Greetings, I am a newcomer here and I hope that my message is clear. My current challenge involves trying to incorporate jQuery into node.js, but unfortunately, all my efforts have ended in failure. I have spent hours attempting to resolve this issue to no ...

Arranging an array of files in a file manager based on their file types

Currently working on a file manager tool for users, the initial version is quite basic and it simply lists all folders and files within their designated directory. <?PHP function getFileList($dir) { // an array to store the results $retval ...

Share an entire /folder through an express server

I am currently working on an express server setup, and I am looking to streamline my route handling for managing an entire directory structure. root /html /css /js /app.js /images /index.html /some-other.htm ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

Hide only the table that is being clicked on, not all tables

Essentially, I am using document.querySelectorAll() to retrieve an array of div elements. In my function, handleClick(), each time the button is clicked, I want to hide the table associated with that specific button. This is the current situation: https:/ ...

JavaScript for Verifying Phone Numbers

After extensive research and tutorials, I am still unable to figure out what is going wrong with my work. I have a button that looks like this: Despite Stack Overflow causing some trouble for me, please ignore the missing class as it is there. This is no ...

Utilize MySQL/Javascript to determine percentages

I'm facing a challenge with an SQL query in Entrinsik's Informer. I need to calculate a percentage using JavaScript on the result, but unfortunately, Informer cannot access data down columns (such as the total for the percentage). Therefore, I ha ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

How can JavaScript determine if this is a legitimate JS class?

I'm currently in the process of converting a React.js project to a next.js project. In my project, there's a file named udf-compatible-datafeed.js. import * as tslib_1 from "tslib"; import { UDFCompatibleDatafeedBase } from "./udf-compatibl ...