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);
Answer from trincot on Stack Overflow
🌐
Programiz
programiz.com › javascript › recursion
JavaScript Recursion (with Examples)
Here, we have a recursive function greet() without a base case. As you can see, greet() keeps calling itself until the program runs into an error (RangeError). ... Before we wrap up, let’s put your knowledge of JavaScript Recursion to the test!
🌐
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 |
So before we learn how to write a recursive function, let's understand each part needed to build it. The MDN web docs explain that the reduce() method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value.
🌐
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.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-recursion-function-exercise-4.php
JavaScript recursion function: Compute the sum of an array of integers - w3resource
if (my_array.length === 1) { return my_array[0]; } else { // Recursive case: pop the last element and add it to the sum of the remaining elements. return my_array.pop() + array_sum(my_array); } }; // Example usage: Calculate and print the sum of elements in the array [1, 2, 3, 4, 5, 6]. console.log(array_sum([1, 2, 3, 4, 5, 6])); ... See the Pen javascript-recursion-function-exercise-4 by w3resource (@w3resource) on CodePen.
🌐
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.
🌐
freeCodeCamp
freecodecamp.org › news › flatten-array-recursion
How to Flatten an Array in JavaScript Using Recursion
August 18, 2022 - Your job is to return a new array which contains all the numbers in a linear fashion without any nesting. Keep in mind that the nesting can be any level deep. Here's the solution to our problem using recursion: ... If you carefully look at the function named recursion in the above code snippet, we are checking if the array element that we are currently at is an array or not.
🌐
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 - So a list is recursively defined as a head attached to a tail, which may be empty. In Haskell’s pattern-matching syntax, this is often written as (x:xs), where x is an element, and xs is a (possibly empty) list. It’s easy to think of map as iterating over an array, applying map to each element, and adding the new value to a new array. function map(fn, array) { let ret = []; for (let i = 0; i < array.length; i++){ ret.push(fn(array[i])); } return ret; }
Find elsewhere
Top answer
1 of 3
11

You are checking for the presence of key each time through the loop over the object's properties. So you are getting as many values as there are properties on the object. So:

function getValuesByKey(object, key) {
  var values = [];
  recursiveFx(object);
  function recursiveFx(object) {

    if (key in object) values.push(object[key]);
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    for (var property in object) {
      if (object.hasOwnProperty(property)) {
        if (typeof object[property] == "object") {
         recursiveFx(object[property]);
        }
      }
    }
  }
  return values;
} 

Alternative: use JSON.stringify with replacer

Anyway, you can do this more easily with

function getValuesByKey(object, key) {
  var values = [];
  JSON.stringify(object, function(k, v) { 
    if (k === key) values.push(v);
    return v;
  });
  return values;
}

This uses the replacer parameter to JSON.stringify to intercept each key value pair. The stringified value itself we don't need and throw away.

2 of 3
3

Just an idea of recursion:

var data = { "children": [{ "id": "5", "parentid": "0", "text": "Device Guides", "index": "1", "children": [{ "id": "10", "index": "0", "text": "Grandstream GXP-21XX" }, { "id": "11", "index": "1", "text": "Polycom Soundstation/Soundpoint" }, { "id": "23", "parentid": "8", "index": "2", "text": "New Polycom", "children": [{ "id": "5", "parentid": "0", "text": "Device Guides", "index": "1", "children": [{ "id": "10", "index": "0", "text": "Grandstream GXP-21XX" }, { "id": "11", "index": "1", "text": "Polycom Soundstation/Soundpoint" }, { "id": "23", "index": "2", "text": "New Polycom" }] }, { "id": "6", "parentid": "0", "text": "Pre-Sales Evaluation", "index": "0", "children": [] }, { "id": "7", "parentid": "0", "text": "Router Setup Guides", "index": "2", "children": [{ "id": "9", "index": "0", "text": "Sonicwall" }, { "id": "12", "index": "1", "text": "Cisco" }] }] }, { "id": "6", "parentid": "0", "text": "Pre-Sales Evaluation", "index": "0", "children": [] }, { "id": "7", "parentid": "0", "text": "Router Setup Guides", "index": "2", "children": [{ "id": "9", "index": "0", "text": "Sonicwall" }, { "id": "12", "index": "1", "text": "Cisco" }] }] }] };

function getValuesByKey(object, key) {
    var values = [];

    function r(obj) {
        Object.keys(obj).forEach(function (k) {
            if (Array.isArray(obj[k])) {
                obj[k].forEach(r);
                return;
            }
            if (typeof obj[k] === 'object') {
                r(obj[k]);
                return;
            }
            k === key && !~values.indexOf(obj[k]) && values.push(obj[k]);
        });
    }

    r(object);
    return values;
}

document.write('<pre>' + JSON.stringify(getValuesByKey(data, 'id'), 0, 4) + '</pre>');

🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Javascript recursive functions - JavaScript - The freeCodeCamp Forum
October 11, 2020 - Good evening friends Please do anyone has a solid of understanding of recursive functions. I just can’t figure what is happening in the background with the recursive functions. for example function multiply(arr, n) { if (n
🌐
TutorialsPoint
tutorialspoint.com › article › recursively-loop-through-an-array-and-return-number-of-items-with-javascript
Recursively loop through an array and return number of items with JavaScript?
Should return 3 because it makes a total of 3 appearances in the array. Therefore, let’s write the code for this recursive function − · const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]]; const searchRecursively = (arr, query, count = 0, len = 0) => { if(len · The output in the console will be − · 3 · AmitDiwan · Updated on: 2020-08-24T05:41:29+05:30 · 2K+ Views · JavaScript - Recursion Javascript ·
🌐
DEV Community
dev.to › alexmercedcoder › javascript-writing-map-as-a-recursive-function-2854
Javascript - Writing Map as a Recursive Function - DEV Community
January 1, 2021 - Think of higher order functions ... multiple heads to use it in different ways. Recursive functions are functions that call themselves in their definition which can be quite confusing when your first see them....
🌐
DEV Community
dev.to › justin_m_morgan › loops-array-methods-and-recursion-45ng
Loops, Array Methods, and Recursion - DEV Community
November 19, 2021 - In Javascript, it has the form: for(<starting_condition>; <ending_condition>; <how_to_progress_after_each_step>;) { <work_to_do_at_each_step> } While this annotation doesn't directly map to the above described qualities of looping, actual implementations make it more apparent that it does in fact correspond. Let us consider summing a list of 1 million numbers, stored in an array. function forSum(array_of_numbers, sum = 0) { for(let i = 0; i < array_of_numbers.length; i++) { sum += array_of_numbers[i] } return sum }
🌐
Scrimba
scrimba.com › articles › javascript-recursion
Quickly learn recursion in JavaScript with examples
March 21, 2023 - Here are four challenges for you ... we started this article off with) Write a recursive function that accepts an array as its argument and returns the largest value in the array (hint, this works in a similar way to the ...
🌐
Rip Tutorial
riptutorial.com › recursive function
JavaScript Tutorial => Recursive Function
function countEvenNumbers (arr) { // Sentinel value. Recursion stops on empty array. if (arr.length < 1) { return 0; } // The shift() method removes the first element from an array // and returns that element. This method changes the length of the array. var value = arr.shift(); // `value % 2 === 0` tests if the number is even or odd // If it's even we add one to the result of counting the remainder of // the array.
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-understand-recursion-in-javascript
Recursion Guide in JavaScript - GeeksforGeeks
Table of Content Recursively Summing DigitsUsing string manipulation with recursionRecursively Summing DigitsIn th ... The basic method to create an array is by using the Array constructor.
Published   February 14, 2025
🌐
Playcode
playcode.io › javascript › recursion
JavaScript Recursion: Complete Guide with Examples | Playcode
Factorial function factorial(n) { if (n <= 1) return 1; // Base case return n * factorial(n - 1); // Recursive case } console.log("\n--- Factorial ---"); console.log("5! =", factorial(5)); // 3. Sum of array function sumArray(arr) { if (arr.length === 0) return 0; return arr[0] + sumArray(arr.slice(1)); } console.log("\n--- Array Sum ---"); console.log("Sum [1,2,3,4,5] =", sumArray([1, 2, 3, 4, 5]));