Why did the program suddenly cease verifying if it is an Array?

I've been working on flattening an array, but I noticed that my code stopped processing when it encountered a nested Array. The output I'm getting is [ 1, 2, 3, [ [ [Object] ] ] ].

Could someone explain to me why the code isn't continuing through the nested Arrays and why it's failing to concatenate properly? Thank you!

flatten = function(nestedArray, result) {
    result = [];

    each(nestedArray, function(item){

      if(Array.isArray(item)){
          result = result.concat(item);
      } else {
          result.push(item);
      }
    });
return result;
};

flatten([1, [2], [3, [[[4]]]])

Answer №1

When it comes to JavaScript, there isn't a method exactly like each. However, you can achieve similar functionality by using the Array#forEach method in conjunction with a recursive function.

function flattenArray(nestedArray, result) {
  result = [];
  // Iterate through the array
  nestedArray.forEach(function(item) {
    if (Array.isArray(item)) {
      // Recursively flatten inner arrays and combine them
      result = result.concat(flattenArray(item));
    } else {
      result.push(item);
    }
  });
  return result;
};

console.log(flattenArray([1, [2], [3, [[[4]]]]]));

Answer №2

function processArray(element, index, array) {
    if (Array.isArray(element)) {
        element.forEach(processArray);
    } else {
        finalResult.push(element);
    }
};

finalResult = [];
var nestedInputArray = [1, [2], [3, [[[4]]]]];
nestedInputArray.forEach(processArray);

console.log(finalResult);

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

Parent Directory Injector: Prioritizing Injection of Parent Directories

Currently, I am utilizing 'grunt-injector' to inject a list of files using 'app/**/*.js'. However, I am facing dependency errors due to the alphabetical order in which the files are injected. To avoid these issues, I am looking for a so ...

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

Tips for displaying an error message when there is no match found in ng repeat due to filtering

I'm facing an issue with displaying an error message when no match is found after searching in a text box. I've used ng-show to display the message, but it's not working as expected. Can someone assist me with this problem? I am relatively n ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

Having trouble with jQuery getJSON and file invocation in IE9?

JavaScript: var loadNeededDocumentsData = function () { $j.getJSON("customermanagement/documentsCheckJSON.do", function (data) { }); } $j(document).ready(function () { loadNeededDocumentsData(); }); While the code functions correctly in Fir ...

Tips for showcasing information stored in a JSON file: Input a value into the field provided, then utilize AngularJS to retrieve and display the corresponding data based on that specific value

https://plnkr.co/edit/iZqalOkrpSnjIzwvGchO?p=preview Is there a way to retrieve the data associated with each serial number entered in the search box? What elements might be missing from the current code? { "SerialNumbers": { "451651": [{ ...

What is the best way to outline the specifications for a component?

I am currently working on a TypeScript component. component @customElement("my-component") export class MyComponent extends LitElement { @property({type: String}) myProperty = "" render() { return html`<p>my-component& ...

What are some ways to incorporate JQuery with getElementById?

i am trying to retrieve all input elements within a form using JavaScript formEditable = document.getElementById("formid").getElementsByTagName("input"); However, I would like to achieve the same result using jQuery instead formEditable = $("#formid").f ...

Issue with Bootstrap Navbar dropdown functionality not functioning correctly in browsers, but working fine on Codepen

I'm encountering an issue with a dropdown menu in the navbar of my document. The dropdown menu works fine in my codepen but not in my text editor (Sublime). I've tried various solutions and couldn't find a fix, so I'm reaching out here ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

Adding zeroes to specified positions within a 2D array using Python

I am dealing with arrays X = np.array([ [7,2,9], [4,6,5], [1,0,8] ]) Y = np.array([ [5,3,2], [0,7,5], [4,2,6] ]) Executing x = np.argwhere(X > 5) provides me with an array containing the indexes of elements in array X that are greater tha ...

Find the nearest element with a specific class using jQuery

I am currently using jQuery version 1.12.4 for the purpose of retrieving the value from the closest element with a specific class selector. Unfortunately, I am encountering difficulty in selecting the closest element as desired. $(function() { $("[cla ...

Strip away the HTML tags and remove any text formatting

How can I effectively remove HTML tags and replace newlines with spaces within text? The current pattern I am using is not ideal as it adds extra space between words. Any suggestions on how to improve this pattern? replace(/(&nbsp;|<([^>]+)> ...

Saving the previous component's DOM in a React application

Understanding the Root.js File const Root = () => ( <HashRouter> <div> <Route exact path="/" component={Main}/> <Route path="/main/:page" component={Main}/> <Route path="/detail ...

Troubleshooting: Issues with window.location.href and window.open within an iframe

Code Update <div> <button type="button" class="submit btn btn-default" id="btnSubmit">Submit </button> <button type="button">Cancel</button> </div> <script> $("#btnSubmit").click(function(e) { ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

Combining Strings with Arrays of Bytes

When faced with the task of concatenating a String with a byte array, I attempted the following approach: String message = "message to display"; byte[] messageBytes = new byte[message.length()]; try { messageBytes = message.getBytes("UTF-8"); } catc ...

(node:19502) UnresolvedPromiseRejectionNotification: Promise rejection not handled (rejection id: 1): TypeError: Unable to access property 'indexOf' of undefined

I successfully integrated cucumber with nightwatch.js. Here is a snippet of my package.json file: { "name": "learning-nightwatch", "version": "1.0.0", "description": "learning nightwatch", "license": "UNLICENSED", "scripts": { "nightwatch": ...

Tips for enhancing the speed of ngRepeat when working with a large dataset in angular.js

I have a large dataset consisting of thousands of rows with about 10 fields each, totaling approximately 2MBs of data. My challenge is to effectively display this information in a web browser. The most obvious solution involves fetching the data, assigning ...

Retrieve the JSON array value from the observable and pass the information to the frontend

Attempting to retrieve a JSON array from a json-server using observables, then passing the value to the frontend for search functionality on the received JSON array. Created a service and utilized HTTP get method to establish a connection with the server ...