Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

354
Views
How to return the entire array in a recursive JavaScript function?

I have a recursive function to work with nested arrays that are multi-level deep. The code below is supposed to select random elements, one from each level, and combine them into an array (in the order they are printed out in the console). However, the resulting array only contains elements of the highest levels (A, B or C, D or C), nothing below that. What is the reason for that?

const arry = [
  ["A"],
  ["B", "C"],
  ["D", "E"],
  [
    [
      ["F1", "F2"],
      ["G1", "G2"],
      [
        "H1",
        "H2",
        [
          ["I1", "I2", "I3"],
          ["J1", "J2"],
          ["K1", "K2", "K3"],
        ],
      ],
    ],
  ],
];

function rndmElementSelection(array) {
  rndElm = array[Math.floor(Math.random() * array.length)];
  return rndElm;
}

function recursion(array, resultAry = []) {
  array.forEach((element) => {
    if (typeof element === "string") {
      console.log(element);
      resultAry.push(element);
    } else {
      nE = rndmElementSelection(element);
      if (typeof nE === "string") {
        console.log(nE);
        resultAry.push(nE);
      } else {
        recursion(nE);
      }
    }
  });
  return resultAry;
}

console.log(recursion(arry));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The problem is that your recursive call does not pass the second argument.

Without passing it, each recursive call will just populate its own, new array. It does return that array to the caller, but the caller (making the recursive call) ignores that returned value, so all the work of the recursive call is for nothing.

So the easy fix is to change this:

} else {
    recursion(nE);

to this:

} else {
    recursion(nE, resultAry);
about 4 years ago · Juan Pablo Isaza Report

0

Try this:


function recursion(array, resultAry = []) {
  array.forEach((element) => {
    if (typeof element === "string") {
      console.log(element);
      resultAry.push(element);
    } else {
      nE = rndmElementSelection(element);
      if (typeof nE === "string") {
        console.log(nE);
        resultAry.push(nE);
      } else {
        resultAry = [...resultAry, ...recursion(nE)];
      }
    }
  });
  return resultAry;
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!