You're creating a new array instead of passing it to the recursive call.

Do this instead.

DEMO: http://jsfiddle.net/kDtZn/

function addToArray(array) {
    array.push(prompt("Add items to array or 'q' to stop"));
    if (array[array.length-1] == 'q') {
        array.pop();
        document.write(array)
    }
    else {
        addToArray(array);
    }
 }
 addToArray([]);

Now you start with an empty array, and for each recursive call, it passes the same array forward.

Also, I changed it so that it doesn't use .pop() in the if() condition, otherwise you'll always end up with an empty array when it comes time to write it. (The .pop() method actually removes the last item.)

Finally, make sure you're not using document.write after the DOM is loaded. If so, you need to change it to use DOM manipulation methods instead.


You could take a different approach so that you don't need .pop() at all.

DEMO: http://jsfiddle.net/kDtZn/1/

function addToArray(array) {
    var item = prompt("Add items to array or 'q' to stop");
    if (item == 'q') {
        document.body.textContent = array;
    } else {
        array.push(item);
        addToArray(array);
    }
}
addToArray([]);

The reason your while loop didn't work is very likely because of the original .pop() issue.

Answer from user2736012 on Stack Overflow
🌐
Quora
quora.com › How-do-I-add-items-to-an-array-in-JavaScript-recursively-and-return-that-array-1
How to add items to an array in JavaScript recursively and return that array - Quora
How do you iterate over a specific nested array in JavaScript (JavaScript, arrays, nested, key, development)? RelatedIs there a way return an array from recursion? ... Yes! In fact, this is extremely useful - in languages that don’t have iteration, this is how map and filter are implemented! ... For the empty list, return an empty list; otherwise, return a list that is the user-supplied function applied to the first element, plus the result for the rest of the list (recursive call).
Discussions

array.push() recursion in JS
Not quite what you asked, but if you wanted all of the values in a single array, instead of a nested series of arrays, then you could use the .concat() method , instead of the .push() method, though you'll have to do it like this: arr = arr.concat(countdown(n - 1)); Now, with that one line of code changed, you'll end up with an array like this instead: [5, 4, 3, 2, 1] Enjoy! 🙂 More on reddit.com
🌐 r/learnjavascript
7
9
October 17, 2021
Help with Recursive Arrays
Tell us what’s happening: I get how to make the code work. I understand what’s needed to complete it but I cannot visualize how it works in this instance. Where are the variables storing and how are they storing in the correct order? Is there a simulation that goes through each iteration ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
November 13, 2019
recursion - Array decomposing recursive function in JavaScript - Code Review Stack Exchange
What I need is to remove first word from the string again and again until only one word is left, and put it all into array. For example, I have this string as an input: Chicago IL 12345 United Sta... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 7, 2017
recursion - Javascript -> how to recursively add an array of numbers? - Stack Overflow
You want to check the length. ... Sigh. yes. I shouldn't have missed that. Thanks for the explanation! ... function arrayIntSum(array) { if (array.length === 0){ return 0; } else return array.shift() + arrayIntSum(array); } ... you compared a with [] , being a '[]' literal, it has different memory space. and a has different memory space. So they are never equal. so recursion ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › how-to-insert-an-element-into-all-positions-in-an-array-using-recursion-javascript
How to insert an element into all positions in an array using recursion - JavaScript?
October 1, 2020 - That is, if arr is the length N, then the result is an array with N + 1 arrays − · For example, the result of insertAllPositions(10, [1,2,3]) should be − · const output = [ [10,1,2,3], [1,10,2,3], [1,2,10,3], [1,2,3,10] ]; We are required to write this function purely using recursion.
🌐
Medium
medium.com › @natelapinski › recursive-array-methods-better-javascript-through-haskell-62c47b02d08c
Recursive Array Methods. Better Javascript through Haskell. | by Nate Lapinski | Medium
December 30, 2019 - In this short article, we’re going to implement some of the most useful methods on Array.prototype using recursion. The goal is to give you some insight into how map, filter, and reduce work, and to demonstrate how to the think about array operations in Javascript in terms of recursion, similar to how Haskell and other pure languages operate on lists.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Help with Recursive Arrays - JavaScript - The freeCodeCamp Forum
November 13, 2019 - Tell us what’s happening: I get how to make the code work. I understand what’s needed to complete it but I cannot visualize how it works in this instance. Where are the variables storing and how are they storing in the correct order? Is there a simulation that goes through each iteration ...
Find elsewhere
🌐
LaunchCode
education.launchcode.org › intro-to-professional-web-dev › chapters › more-on-functions › recursion-walkthrough.html
11.7. Recursion Walkthrough: The Base Case — Introduction to Professional Web Development in JavaScript documentation
To ease into the concept of recursion, let's start with a loop task. In the Arrays chapter, we examined the join method, which combines the elements of an array into a single string. If we have arr = ['L', 'C', '1', '0', '1'], then arr.join('') returns the string 'LC101'. We can reproduce this action with either a for or a while loop. ... Inside each loop, the code simply adds ...
🌐
freeCodeCamp
freecodecamp.org › news › flatten-array-recursion
How to Flatten an Array in JavaScript Using Recursion
August 18, 2022 - Well in the next index, 4 is also just a number, so push it to the output array. And we're done! Well, why don't you do that same on **index 2 ( [ 3, 4 ] )** of our input array, then? You must be wondering, well it's easy to say that! How are going to do that in code!? This is where recursion comes into the picture.
🌐
Selftaughttxg
selftaughttxg.com › 2023 › 01-23 › how-to-write-a-recursive-function-in-javascript-for-beginners
How to Write a Recursive Function in JavaScript for Beginners |
January 2, 2023 - I came across Dan's recursive function while participating in Scrimba's JavaScriptmas 24-day annual coding event. The day 17 challenge, Pumpkin's Prizes, instructs us to write a function to flatten nested arrays of strings or numbers into a single array.
Top answer
1 of 2
1

Rather than pushing the entire returned array from getBreadcrumb into your result, you can instead push the individual array elements from the returned array using the spread syntax (...):

breadcrumbArray.push(...getBreadcrumb(parentPageId))

Note that the above will fail if the array returned by getBreadcrumb() is very large an exceeds the max-argument count that you can pass to the .push() function. You do always have the option of doing what you're currently doing, and then calling .flat(Infinity) on your returned result. This does add an additional pass over your array though which can be avoided. You can overcome these issues by instead returning a new array, with your returned array spread into that:

function getBreadcrumb(pageId) {
  const { id, slug, title, parentPageId } = getParentPage(pageId);
  return [{ id, slug, title, parentPageId }, ...(parentPageId ? getBreadcrumb(parentPageId) : [])];
}

The above will create a new array, with your {id, slug, ...} object as the first element, followed by either nothing (if parentPageId is falsy), or the array elements from that array returned by the call to getBreadcrumb(parentPageId))

2 of 2
0

Here's a non-recursive approach, use a while loop, and re-call getParentPage():

function getBreadcrumb(pageId) {
  let breadcrumbArray = [];
  let { id, slug, title, parentPageId } = getParentPage(pageId);
  breadcrumbArray.push({ id, slug, title, parentPageId });
  
  // while parentPageId === false, execute getParentPage with found id
  while ( parentPageId ) {
      pageObj = getParentPage(id);
      breadcrumbArray.push(pageObj);
      // update found id and parentPageId for while loop
      id = pageObj.parentPageId;
      parentPageId = pageObj.parentPageId;
  }
  return breadcrumbArray;
}

// okay to ignore the rest...
// parent page mock up, randomly return a parentPageId that equates to false
function getParentPage(pageId) {
  return { id: 1, slug: "slug", title: "title", parentPageId: Math.floor(Math.random() * 2) };
}
console.log(getBreadcrumb(3));

🌐
W3Resource
w3resource.com › javascript-exercises › javascript-recursion-function-exercise-4.php
JavaScript recursion function: Compute the sum of an array of integers - w3resource
... // Function to calculate the sum of elements in an array using recursion. function arraySumRecursive(arr, index = 0) { // Base case: if the index exceeds the array length, return 0. if (index >= arr.length) { return 0; } else { // Recursive ...
Top answer
1 of 2
1

The key to building up an array with recursion is the concat() method, which will properly return a copy of the array all the way up the recursion stack.

In the example below, objects that match your criteria get added in with push(), while child objects are searched through recursively and their results are concatenated to the result array. For simplicity I used the results of what your getFolder()function would return in the data:

var structure = {
  folder: {id:1, name:'name1'}, //getFolder(1, 'name1'),
  children: [{
    folder: {id:2, name:'name2'}, //getFolder(2, 'name2'),
    children: [{
      folder: {id:4, name:'name2'}, //getFolder(4, 'name2'),
      children: []
    }]
  }, {
    folder: {id:3, name:'name3'}, //getFolder(3, 'name3'),
    children: []
  }]
};

function searchAll(object, criteria) {
  var i, j, result = [];

  for (i in object) {
    if (i === criteria.type && object[i][criteria.index] === criteria.value) {
      result.push(object);
    } else if (i === 'children' && object[i].length > 0) {
      for (j = 0; j < object[i].length; j++) {
        result = result.concat(searchAll(object[i][j], criteria));
      }
    }
  }

  return result;
}

console.log(searchAll(structure, {type: 'folder', index: 'name', value: 'name2'}));

Edit: link to JSFiddle because it looks like the SO code snippet stops the recursion, the results should be correct (2 objects with the data you wanted) https://jsfiddle.net/fswmxk7h/

2 of 2
0

The main issue is that you are bailing out and not appending to results when you find a match (return data;). This is a hopefully simpler and working version. You also have a problem that you are both passing 'results' to the recursion, and pushing the resulting array onto results, which isn't what you wanted. This is hopefully correct for the style you are going for (untested):

var searchAll = function (data, searchFor, results) {
    results = results || [];
    if (data[searchFor.type] &&
        data[searchFor.type][searchFor.index].indexOf(searchFor.value) !== -1) {
        results.push(data); // now carry on an recurse children
    }
    if (data.children) {
        for (var i = 0; i < data.children.length; i++) {
            // use results arg to avoid array creation on recursion:
            searchAll(data.children[i], searchFor, results);
        }
    }
    return results;
};

searchAll(structure, {
    type: 'folder',
    index: 'name',
    value: 'name2'
});
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript recursive function
JavaScript Recursive Function
November 15, 2024 - This tutorial shows you how to use the recursion technique to develop a JavaScript recursive function, which is a function that calls itself.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › advanced working with functions
Recursion and stack
The code is short and easy to understand (hopefully?). That’s the power of recursion. It also works for any level of subdepartment nesting. ... We can easily see the principle: for an object {...} subcalls are made, while arrays [...] are the “leaves” of the recursion tree, they give immediate result.