Exploring nested arrays with recursive looping

I have been working on solving this challenge using recursion because I enjoy the challenge. The task at hand involves taking an array of arrays and transforming it into a single array with all the values combined. While I have made good progress, I am encountering an issue where the new array I am appending to keeps resetting after each recursion. I would greatly appreciate any advice or suggestions to help me overcome this obstacle.

var multiArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]

const flattenArrays = function (arr) {
  let result = [];

  arr.map(element => {
    if (Array.isArray(element)) {
      console.log('Is Array ---> ', element)
      flattenArrays(element);
    } else {
      console.log('Result ----->', result)
      console.log('Else     --->', element)
      result.push(element);
    }

  });

  return result;

};

console.log('Result ----->', flattenArrays(multiArray)); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Answer №1

To utilize the results from calling flatten(element), it is recommended to employ the spread syntax like this:

output.push(...flatten(element));

Additionally, consider replacing the map call with Array.forEach() since the returned array isn't being used.

For instance:

const flatten = function(arr) {
  const output = [];

  arr.forEach(element => {
    if (Array.isArray(element)) {
      output.push(...flatten(element));
    } else {
      output.push(element);
    }

  });

  return output;

};

var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]


console.log(flatten(myArray)); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Answer №2

When dealing with nested arrays that do not have nested arrays themselves, recursion may not be necessary:

Array.prototype.flatMap provides a simple solution to flatten such arrays:

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is similar to using map() and then flat() with a depth of 1, but flatMap() is more convenient and slightly more efficient.

For example:

[[1, 2],[3, 4, 5], [6, 7, 8, 9]].flatMap(xs => xs);
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

If you encounter deeply nested arrays like

[[1, 2, [3, 4, 5, [6, 7, 8, 9]]]]

Then a recursive flatMap function remains a solid choice:

const flatten = xs =>
  xs.flatMap(x =>
    Array.isArray(x)
      ? flatten(x)
      : x);

flatten([[1, 2, [3, 4, 5, [6, 7, 8, 9]]]]);
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Although, the introduction of Array.prototype.flat renders this obsolete as it can flatten deeply nested arrays:

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

If you are unsure of the depth, simply set it to Infinity:

[[1, 2, [3, 4, 5, [6, 7, 8, 9]]]].flat(Infinity);
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

It is important to note that flat is not widely supported in all modern browsers yet. If Babel is an option in your project, using it may be beneficial.


While creating a custom recursive function is possible, exploring the native language options is also recommended.

Answer №3

Here is my approach

let numbers = [[10, 20],[30, 40, 50], [60, 70, 80, 90]]
const flattenArray = (arr, result = []) => {
   if (Array.isArray(arr)) {
      arr.forEach(item => {
         flattenArray(item, result)
      })
   } else {
      result.push(arr)
   }
   return result
}
console.log(flattenArray(numbers))

Answer №4

let numbers = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]

function flattenArray (arr) {
  return arr.reduce((acc, element) => {
    if (Array.isArray(element)) return [...acc, ...flattenArray(element)];
    acc.push(element);
    return acc;
  }, []);
}

console.log(flattenArray(numbers))

Answer №5

If you're looking for a solution without relying on any 'magic':

function flattenArray(input, output){
  if(!output)
    output=[];
  if(!Array.isArray(input))
    output.push(input);
  else
    for(var i=0;i<input.length;i++)
      flattenArray(input[i],output);
  return output;
}

var testArray = [[1, 2],[3, 4, 5], 6, [[7, 8], 9]];
console.log(flattenArray(testArray).join());

This approach follows the traditional recursive method often taught in schools.

The main issue in your code lies in the recursive call: flatten(element);. The function doesn't receive the partial result, output (unlike the code above that includes an 'optional' parameter initialized to [] when absent), and whatever it returns is not appended to the existing output either.

You have two options to fix this:

var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]

const flatten = function (arr, output) { // added output
  if(!output)                            // initialize if missing
    output = [];

  arr.map(element => {
    if (Array.isArray(element)) {
      console.log('Is Array ---> ', element.join())
      flatten(element, output);          // added output
    } else {
      console.log('Output ----->', output.join())
      console.log('Else     --->', element)
      output.push(element);
    }

  });

  return output;

};

console.log('Return -----> ', flatten(myArray).join()); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

(Included some .join() methods too, so the log displays horizontally)

Alternatively, the second fix:

var myArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]

const flatten = function (arr) {
  let output = [];

  arr.map(element => {
    if (Array.isArray(element)) {
      console.log('Is Array ---> ', element.join())
      output = output.concat(flatten(element));     // concatenate with result
    } else {
      console.log('Output ----->', output.join())
      console.log('Else     --->', element)
      output.push(element);
    }

  });

  return output;

};

console.log('Return -----> ', flatten(myArray).join()); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

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 compare two arrays in my JSON data?

Hello, I'm trying to compare two arrays - one from my JSON data and the second from a regular array. Specifically, I want to check if the ids of "cm:taggable" exist in my secondArray. JSON { "entry": { "isFile": true, "createdByUs ...

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...

Is there a way to determine if a directory is empty using Node.js?

Quite a while back, I submitted a question related to PHP. Now I'm facing a similar situation with Node.js where the code below appears to be sluggish when used in a loop - is there a way to achieve this using only vanilla JavaScript in pure Node.js w ...

You will encounter a TypeError with the message "Super expression must be null or a function" when attempting to export a named class

I'm experimenting with components. I have a default export in place but now I think I need to create a named class for my next export. Take a look at the code below: export default Users; import React from 'react'; export class UsersTest e ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...

Is there a way to transfer the content of a div into a fresh window while retaining its original formatting

Here is a way to copy a new page: var yourDOCTYPE = "<!DOCTYPE html..."; // the doctype declaration var printPreview = window.open('about:blank', 'print_preview'); var printDocument = printPreview.document; printDocument.open(); pri ...

Obtain geographic information using a JSON fetch from a map

I am facing an issue while integrating Laravel API data into React. Although I can see the JSON data in the console after fetching it, I encounter an error when I try to display it in a table for listing. The error states that my .map function is not recog ...

I am interested in retrieving an array

Here is the array I am working with { Colors: 'Blues', Department: 'Clearance', Size: [ 'Runners', 'Custom Sizes' ], Shape: 'Round', Designer: 'B. Smit', } The desired output should be ...

What sets an array apart from a pointer in the C programming language?

In this particular code snippet, #include<stdio.h> int main(){ int a = 1025; int *p; p = &a; char *p0; p0 = (char *)p; //print("\n%d %d", *p0, *(p0+1)); printf("\n%d and %d", *p0, p0[1]); } Output: 1 and 4 char &am ...

calling object functions using additional parentheses

After reviewing the passport.js documentation, I came across this piece of code: app.get('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!u ...

Set the display property of all child elements within the DIV to none

CSS <div class="container"> <span></span> <input type="text"> </div> JavaScript function hideElements(){ let container = document.querySelector(".container"); let elements = ...

Encountered a problem while initiating the HTTP server in a node.js

I'm currently attempting to initiate an HTTP server from my index.js file. After going through The Node Beginner tutorial, I've been encountering errors every time I try to start the server using the provided code: Server.js - var http = re ...

Java's multi-dimensional data structure allows for intricate organization and storage of

I am currently facing a challenge where I need to design a data structure with specific syntax requirements: [ status: "success", statusDescription: "statusDescription" count: "5", states: [ [stateId: "1", stateDescription: "1 description"], [stat ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...

Is there a problem with `window.google` being undefined in a React

Every time I call window and use console log, a google prop appears as shown below: https://i.sstatic.net/dSMs8.png But then when I attempt to call window.google, it returns undefined. Am I overlooking something here? ...

Troubleshooting JSON Array Index Problems

I'm having trouble reaching index 3 in the array using the javascript options on my webpage. The final question "are you satisfied with your choice?" is not showing up for me. I'm not sure what I might be missing or doing incorrectly in this sit ...

Storing API data in localStorage using VueJS: A step-by-step guide

As I work on practicing building a simple SPA with VueJS, one of my current tasks involves listening to an API and storing certain data in the browser's localStorage. However, my experience with VueJS is still limited, so I'm unsure about how to ...

What is the reason for my result showing as Object { } rather than MyObj { }?

When utilizing the web development tools console, if a browser object is typed, it will return as "console." > console Console { } > console.log(console) undefined > Console { } This behavior applies to all browser objects. However, when I try ...