At what point is arr[ i ] added to the new array (flat) when flattening an Array - through flat.push() or flat.concat()?

I grasp the concept, but I am struggling to understand the process.

Once it reaches this line:

flat = flat.concat(flatten(arr[i]))

I fail to comprehend how that specific subarray which is about to be iterated through ends up in flat = [].

I realize that when the function is called again, the subarray is essentially being treated as if it were not a subarray and begins to loop through its elements.

The arr[i] eventually reaches flat.push(arr[i]);

At that point, are the items within the arr[i] pushed into flat = [], or are they directed to flat.concat(flatten(arr[i])) to be resolved and concatenated once the entire subarray has been traversed?

My confusion lies in whether the items are directly pushed into flat = [] using flat.push(arr[i]) or if there is data present to be able to .concat at the line flat.concat(flatten(arr[i]))

What am I overlooking?

    const arr = [[1, 2, 3], [4, [5, 6]], [[7], [8, [9]]], 10]

    function flatten(arr) {
        let flat = [];
        for (let i = 0; i < arr.length; i++) {
            if (Array.isArray(arr[i])) {
                flat = flat.concat(flatten(arr[i]));
            } else {
                flat.push(arr[i]);
            }
        }
        return flat;
    }

Answer №1

It's a simple and effective recursive algorithm

This function takes either an array or an element and creates a new array by concatenating the flattened array or the element

Essentially achieving the same outcome as Arr.flat(Infinity)

You can verify this with the provided code snippet below

 const arr = [[1, 2, 3], [4, [5, 6]], [[7], [8, [9]]], 10]

 function flatten(arr) {
     let flat = [] ;
     for (let i = 0; i < arr.length; i++) {
       if (Array.isArray(arr[i])) {
         flat = flat.concat(flatten(arr[i]));
       } else {
         flat.push(arr[i]);
       }
     }
     return flat ;
   }

console.log(flatten(arr))
console.log(arr.flat(Infinity))

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

Implementing a redirect and setting a background image dynamically in ASP.NET using code-behind

I have a section in my PHP template with a onclick event handler. My goal is to redirect users to another page when they click on this section. Here's what I've attempted: HTML: <section id="header" onclick="window.location.href='Anoth ...

The variable in my scope is not reflecting the changes in the HTML view

Here is my code for handling file attachments in AngularJS: $scope.attachments = []; $scope.uploadFile = function(files){ for(var i=0; i<files.length; i++){ $scope.attachments.push(files[i]); console.log($scope.attachments.length); } } ...

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...

When Custom Route Provider is not a valid function

This question has been revised since this morning. I am working with two distinct modules, 'admin' and 'authorization'. Within the provider block of the authorization module, I utilize $routeProvider to add an identical route to all ro ...

Ways to determine if prototype methods vary

Is there a technique to verify if functions are distinct despite originating from the same prototype? I'm inquiring because I want to save functions in an array, and when attempting to delete one, it removes all functions due to sharing prototypes. ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

How to use the transform function in JavaScript

Hey there, I'm looking to create a new function. I am just starting out with javascript. I want to wrap the code below in a function like: ConfirmDelete() { }; This function should perform the same action as this code snippet: $('.btn-danger ...

Performing a single database call to insert multiple subdocuments at once

If I have a document containing an array of objects. Data = { _id: 1, total_amount: 0, subDataArray: [ { _id: 1, amount: 0 }, { _id: 2, amount: 1 }, ... ] } Updating the total_amount can be done simply like ...

It is not possible to remove two cookies simultaneously

Yesterday, I found myself in a cookie conundrum with two cookies called access_token and refresh_token. I was struggling to figure out how to delete both of these cookies at once: const logout = (req, res) => { res.clearCookie('access_token&a ...

How to troubleshoot an Ionic exception occurring during the execution of any Ionic command?

Whenever I attempt to run an ionic command, I keep encountering this error message: { Error at FatalException.Exception (C:\Users\crist\AppData\Roaming\npm\node_modules\ionic\node_modules\@ionic\cli-u ...

How can a Dictionary of Array of Strings be created in Swift when the Dictionary entry is nil?

I have been experimenting with Swift to learn how to work with Dictionary and Array types in order to perform simple tasks. My initial attempt involved creating functions for manipulating a list of strings by grouping anagrams together in the same array! ...

AngularJs: The ability to rate or rate functionality

I've been attempting to incorporate a likes/dislikes feature into my project, but it doesn't seem to be functioning correctly. As someone new to this type of functionality, I could use some guidance. Below is the snippet of code that outlines wh ...

Retrieve the Express session using the session ID (sid)

I am faced with the challenge of setting up multiple websocket servers that interact with users through a centralized http server. When a user logs in, the Express program creates a session and stores the username within it. The user is then directed to a ...

Is there a way to extract only the titles from this JSON array? (using JavaScript/discord.js)

How can I extract the "title" values from this JSON array using JavaScript? I need to retrieve all the "title"s and store them in a new array like shown below: array( `hey title1`, `hey title2`, ... ) I am unsure of the number of titles we will receive, b ...

"Exploring the Latest Features of NextJS 13: Enhancing Server

Currently, I am in the process of familiarizing myself with NextJS 13 and its new APP folder structure. I am facing a challenge in updating data on server components without needing to reload the page or the app. My HomePage server component fetches a list ...

Arrays through expressions

Within my PHP code, there is a variable that receives data from a URL in the following format: $data = "data_id=value1/config/value2/config/value3"; This data is always structured as follows: data_id = initial parameter value / config / -> serve ...

How can we stop the brief display of a hidden div from occurring?

I have two divs on my webpage - one to display if JavaScript is disabled, and another if JavaScript is enabled. The issue I am facing is that even when JavaScript is not disabled, the div containing the message stating that JavaScript is disabled briefly ...

Accordion elements that are active will move all other content on the page

I am currently working on creating an accordion using the following code: https://codepen.io/rafaelmollad/pen/JjRZbeW. However, I have encountered a problem where when clicking on one of the accordion items, the content expands and pushes the title upward. ...

Sending data from express js to a different server

Currently, I am faced with a scenario where I need to send a file from Jquery to my Express server and then transfer that request to another server without parsing the file in the Express server. Below are the code snippets I have been using so far: Jquery ...

Retrieving the total count of data entries from the JSON server endpoint

Working on a practice application with the JSON server serving as the backend, I have a question. Is there a way to determine the total number of records at an endpoint without actually loading all the records? For example, if my db.json file contains da ...