Stack your way to flattening an array

I have been experimenting with flattening an array using an iterative approach, incorporating a stack-like structure. My goal is to flatten the array up to a certain depth for the sake of learning and exploration.

Here is what I have come up with so far:

function flattenArray(arr, depth = 1) {

    let flattened = [];
    let index = 0;

    let currentDepth = depth;

    for (let element of arr) {
        flattened.push(element);
        currentDepth = depth;

        while(index < flattened.length) {
            if (Array.isArray(flattened[index]) && currentDepth !== 0) {
                flattened.splice(index, 1, ...flattened[index]);
                currentDepth--;

            } else {
                index++;
            }
        }


    }

    return flattened;
}

However, I encountered an issue when trying to flatten a nested level such as [[3], 4, [5, [6]] because it gets stuck at the depth of '3' without reversing back.

Is there a simple adjustment that can be made to address this issue?

The original array I used was

flattenArray([[1],2,[[3], 'ddd', [4,[5]]]], 2)
, where my expected output would be [1,2,3,'ddd',4, [5]].

The same issue persists even when implementing this using a traditional stack method.

Answer №1

If you utilize the concat and reduce methods, achieving a clean solution is possible:

const flatten = (array, depth) => {
  if(!depth) return array;
  while(depth > 0) {
    array = array.reduce((pre, curr) => pre.concat(curr), []);
    depth--;
  }
  return array;
}

const flat = flatten([1, 2, ['a', 3], [4, [6, 4]], 3, [1, 3], [[['a', 2], 2, 'b'], 'c', 3], 4], 2);
console.log(flat)

The function iterates over the array depth times. During each iteration, it uses concat to combine each element from the previous array into a new array. The key concept here is that concat has two modes of operation:

  1. When given a non-array parameter, it simply adds the element to the original array.
  2. When given an array parameter, it appends every element in the provided array onto the original one.

Essentially, the essence of "flattening" is already encapsulated in concat itself; all that's left is to repeat that process depth times.

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

Putting text file characters into an array

Having recently started learning C, I am facing a challenge with an assignment. The task is to write a program that takes a file name as a command line argument and then prints the contents of the file. However, instead of displaying the actual text from t ...

What is the process for including jQuery js files in a React application?

I recently made the transition to React in order to create a single page application. Prior to this, I had 8 HTML files and 8 JS files that were linked using script tags like so: <script src="pathHere"> </script> With React, the HT ...

An elementary glossary outline made with jQuery

I am a jQuery beginner and I need assistance creating a dictionary list. The challenge I face is that each definition should be displayed under its own row of 3 words on desktop, 2 words on tablet, and as a single word in an accordion system on mobile. On ...

Sharing JSON data between two Backbone views

Could you provide some guidance on how to pass dynamic JSON data from one view to another? In the initial view, I am creating the JSON object using the following syntax: json.push({ first: value, second: value }); ...

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

EaselJS BitmapAnimation has delay when using gotoAndPlay

I have created a requirejs module that enhances the functionality of a BitmapAnimation by allowing it to move around the stage at a specific speed and transition to another looped animation once reaching its destination. The issue I am encountering is a n ...

Exploring the power of jQuery's deferred method and utilizing the ajax beforeSend

Using the deferred object in $.ajax allows for: Replacing the success-callback with the deferred-method done() Replacing the error-callback with the deferred-method fail() And replacing the complete-callback with always() When using: var jqxhr = $.ajax ...

Tips for accessing a web service using JavaScript (AJAX)

I have two projects: one is a web service and the other is an ASP.NET web project. I am trying to insert data using JSON (with AJAX). I tested the web service file with code behind and it works fine, but I'm encountering an error with the JavaScript ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

ReactJs - Organize your data with the sort method

In my React application, I have a table that fetches its data from an API. I need to implement sorting for one of the columns. The values in this column are usually strings of numbers but sometimes can be equal to "-" (Dash). Below is the sort function I ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

`Node.js encountering issues with undefined JSON Array values`

I am facing an issue while trying to extract an array of strings from a JSON file. Although I am able to successfully load the JSON array, I am encountering difficulties in accessing the actual data within it. The structure of my JSON file is as follows: ...

Is there a way to create a slider within the card deck group using Bootstrap Vue?

I followed a tutorial on creating card deck groups which can be found here. Here is the script I used: <template> <div class="animated fadeIn"> <b-card-group deck v-for="row in formattedClubs"> <b-card v-for="club in r ...

"Revamp the appearance of the div element upon clicking elsewhere on the

function replace( hide, show ) { document.getElementById(hide).style.display="none"; document.getElementById(show).style.display="flex"; } @import url('https://fonts.googleapis.com/css2?family=Allerta+Stenci ...

What is the best way to arrange a GeoJSON features array based on a specific property value?

I need help sorting a GeoJSON file based on a property and then slicing it to keep only the top 5 features. For instance, I want to take this GeoJSON and arrange it in descending order by the incidents property: ... [ -75.1972382872565 ...

Adding a JavaScript variable into a Django template tag

This particular situation has been presenting a challenge for me. So far, I have been using query parameters instead of a variable within the {% url %} tag. However, I can't help but wonder if there is a way to achieve this: I am interested in includ ...

Refresh and maintain the default dates in the datepicker

Here is the HTML code snippet that I am working with: <div style="display: inline-block; font-weight: bold;"> <label for="fromDateRange">From:</label> <div id="fromDateRange"></div> </div> <div style="margin ...

What are some techniques for creating a volumetric appearance with THREE.Mesh in WebVR?

Currently, I am in the process of transferring an existing three.js project to WebVR with Oculus Rift compatibility. This application takes an STL file as input, generates a THREE.Mesh based on it, and displays it in a virtual scene. While I was able to su ...

The Name 'require' could not be found (TS2304)

My app is encountering a build error with Webpack, specifically due to awesome-typescript-loader. The error message reads as follows: ERROR in [at-loader] ./src/app/app.ts:6:13 TS2304: Cannot find name 'require'. Here is the code snippet cau ...