Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8582457
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T21:17:49+00:00 2026-06-11T21:17:49+00:00

Scenario: I’m searching for a specific object in a deep object. I’m using a

  • 0

Scenario: I’m searching for a specific object in a deep object. I’m using a recursive function that goes through the children and asks them if I’m searching for them or if I’m searching for their children or grandchildren and so on. When found, the found obj will be returned, else false. Basically this:

obj.find = function (match_id) {
    if (this.id == match_id) return this;
    for (var i = 0; i < this.length; i++) {
        var result = this[i].find(match_id);
        if (result !== false) return result;
    };
    return false;
}​

i’m wondering, is there something simpler than this?:

var result = this[i].find(match_id);
if (result) return result;

It annoys me to store the result in a variable (on each level!), i just want to check if it’s not false and return the result. I also considered the following, but dislike it even more for obvious reasons.

if (this[i].find(match_id)) return this[i].find(match_id);

Btw I’m also wondering, is this approach even “recursive”? it isn’t really calling itself that much…

Thank you very much.

[edit]

There is another possibility by using another function check_find (which just returns only true if found) in the if statement. In some really complicated cases (e.g. where you don’t just find the object, but also alter it) this might be the best approach. Or am I wrong? D:

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T21:17:50+00:00Added an answer on June 11, 2026 at 9:17 pm

    Although the solution you have is probably “best” as far as search algorithms go, and I wouldn’t necessarily suggest changing it (or I would change it to use a map instead of an algorithm), the question is interesting to me, especially relating to the functional properties of the JavaScript language, and I would like to provide some thoughts.

    Method 1

    The following should work without having to explicitly declare variables within a function, although they are used as function arguments instead. It’s also quite succinct, although a little terse.

    var map = Function.prototype.call.bind(Array.prototype.map);
    
    obj.find = function find(match_id) {
        return this.id == match_id ? this : map(this, function(u) {
            return find.call(u, match_id);
        }).filter(function(u) { return u; })[0];
    };​
    

    How it works:

    1. We test to see if this.id == match_id, if so, return this.
    2. We use map (via Array.prototype.map) to convert this to an array of “found items”, which are found using the recursive call to the find method. (Supposedly, one of these recursive calls will return our answer. The ones which don’t result in an answer will return undefined.)
    3. We filter the “found items” array so that any undefined results in the array are removed.
    4. We return the first item in the array, and call it quits.
      • If there is no first item in the array, undefined will be returned.

    Method 2

    Another attempt to solve this problem could look like this:

    var concat = Function.prototype.call.bind(Array.prototype.concat),
        map = Function.prototype.call.bind(Array.prototype.map);
    
    obj.find = function find(match_id) {
        return (function buildObjArray(o) {
            return concat([ o ], map(o, buildObjArray));
        })(this).filter(function(u) { return u.id == match_id })[0];
    };
    

    How it works:

    1. buildObjArray builds a single, big, 1-dimensional array containing obj and all of obj‘s children.
    2. Then we filter based on the criteria that an object in the array must have an id of match_id.
    3. We return the first match.

    Both Method 1 and Method 2, while interesting, have the performance disadvantage that they will continue to search even after they’ve found a matching id. They don’t realize they have what they need until the end of the search, and this is not very efficient.

    Method 3

    It is certainly possible to improve the efficiency, and now I think this one really gets close to what you were interested in.

    var forEach = Function.prototype.call.bind(Array.prototype.forEach);
    
    obj.find = function(match_id) {
        try {
            (function find(obj) {
                if(obj.id == match_id) throw this;
                forEach(obj, find);
            })(obj);
        } catch(found) {
            return found;
        }
    };​
    

    How it works:

    1. We wrap the whole find function in a try/catch block so that once an item is found, we can throw and stop execution.
    2. We create an internal find function (IIFE) inside the try which we reference to make recursive calls.
    3. If this.id == match_id, we throw this, stopping our search algorithm.
    4. If it doesn’t match, we recursively call find on each child.
    5. If it did match, the throw is caught by our catch block, and the found object is returned.

    Since this algorithm is able to stop execution once the object is found, it would be close in performance to yours, although it still has the overhead of the try/catch block (which on old browsers can be expensive) and forEach is slower than a typical for loop. Still these are very small performance losses.

    Method 4

    Finally, although this method does not fit the confines of your request, it is much, much better performance if possible in your application, and something to think about. We rely on a map of ids which maps to objects. It would look something like this:

    // Declare a map object.
    var map = { };
    
    // ...
    // Whenever you add a child to an object...
    obj[0] = new MyObject();
    // .. also store it in the map.
    map[obj[0].id] = obj[0];
    
    // ...
    // Whenever you want to find the object with a specific id, refer to the map:
    console.log(map[match_id]); // <- This is the "found" object.
    

    This way, no find method is needed at all!

    The performance gains in your application by using this method will be HUGE. Please seriously consider it, if at all possible.

    However, be careful to remove the object from the map whenever you will no longer be referencing that object.

    delete map[obj.id];
    

    This is necessary to prevent memory leaks.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Scenario: I am calling a function that returns a field that the user enters
Scenario- I have a method that returns an object retrieved from an NSMutableArray similar
Scenario is that we send out thousands of emails through SMTP server. Content is
Scenario I'm parsing emails and inserting them a database using an ORM (NHibernate to
Scenario first :- I'm using Entity Framework to do some queries, to build my
Scenario While using the Maven Ant Task artifact:deploy , I'm encountering the error java.lang.OutOfMemoryError:
Scenario: Most smartphones have a high resolution camera that generates photos that may range
Scenario : I'm currently trying to build a poor man's Google Maps using scripts
Scenario: An MVC3 app that uses constructor injection to provide services for a given
Scenario: There are multiple C structs, each of which contains a function pointer to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.