Recursive search in array of objects JavaScript? [SOLVED]


Written by - Olorunfemi Akinlua
Reviewed by - Deepak Prasad

Introduction

Recursive search is a technique for traversing a data structure and searching for an element or elements that match a specific condition. In JavaScript, this can be particularly useful when working with arrays of objects.

One common use case for a recursive search is to find an object within an array that has a specific property value. In this article, we will discuss how to carry out a recursive search in an array of objects.

 

Example-1: Recursive search in an array of objects

For example, consider an array of objects representing a list of employees in an organization. Each object might have properties such as name, title, and department. If we wanted to find all employees in the marketing department, we could use a recursive search to iterate through the array and return a new array containing only the objects that have a department property equal to "marketing".

To implement a recursive search in JavaScript, we can use a function that takes two arguments: the array to search, and the condition we want to match. The function should first check if the array is empty; if it is, it should return an empty array. If the array is not empty, the function should take the first element in the array and check if it matches the condition. If it does, it should add that element to the results array. If it does not, it should call itself with the remaining elements in the array.

Here is an example of a recursive search function that finds all objects in an array that have a department property equal to "marketing":

function search(array, condition) {
    if (array.length === 0) {
        return [];
    }
    const [head, ...tail] = array;
    if (condition(head)) {
        return [head, ...search(tail, condition)];
    }
    return search(tail, condition);
}

This function works by using the destructuring assignment syntax to extract the first element in the array (head) and the rest of the elements (tail). It then checks if the head element matches the condition using the provided condition function. If it does, it adds it to the results array using the spread operator (...). If it does not, it simply calls itself with the remaining elements in the array.

To use this function, we can pass in an array of objects and a function that checks the department property of each object

const employees = [
    { name: "Alice", title: "Manager", department: "Marketing" },
    { name: "Bob", title: "Developer", department: "Engineering" },
    { name: "Charlie", title: "Manager", department: "Marketing" },
    { name: "Dave", title: "Designer", department: "Design" },
];

const marketingEmployees = search(
    employees,
    (employee) => employee.department === "Marketing"
);

console.log(marketingEmployees);

Output

[
  { name: 'Alice', title: 'Manager', department: 'Marketing' },
  { name: 'Charlie', title: 'Manager', department: 'Marketing' }
]

This recursive search function can be useful in various situations where you need to find specific elements within an array of objects. It is a simple and efficient way to filter an array using a custom condition.

 

Example-2: Search nested array of objects using Array.prototype.find() method

To find a specific value in a nested array of objects in JavaScript, we can use the Array.prototype.find() method. The find() method returns the value of the first element in the array that satisfies the provided testing function.

Here is an example of using the find() method to find an object with a specific value in a nested array of objects:

let nestedArray = [
    {
        id: 1,
        name: "Amit",
        children: [
            {
                id: 2,
                name: "Sanjeev",
                children: [
                    {
                        id: 3,
                        name: "Pooja"
                    },
                    {
                        id: 4,
                        name: "Rahul"
                    }
                ]
            },
            {
                id: 5,
                name: "Arpita"
            }
        ]
    },
    {
        id: 6,
        name: "Kapil",
        children: [
            {
                id: 7,
                name: "Rakhi"
            }
        ]
    }
];

let findValue = (arr, val) => {
    for(let obj of arr){
        if (obj.name === val) {
            return obj;
        }
        if(obj.children){
            let result = findValue(obj.children, val);
            if (result) {
                return result;
            }
        }
    }
    return undefined;
};


let result = findValue(nestedArray, "Rahul");
console.log(result); 
// Outputs: { id: 4, name: "Rahul" }

In this example, the function uses a for loop to iterate over the array and check if the name of the object is equal to the value passed as val, if it is, it returns the object. If the object has a children key, it recursively calls the findValue function with the children array as the first parameter and the val as the second parameter. It uses an if else statement to check if the recursion returns an object and if it does it returns the object.

This function will check all elements of the array and recursively check all children arrays until it finds the first object that matches the specified value.

 

Example-3: Perform recursive search using index value

In JavaScript, you can perform a recursive search in an array of objects by defining a function that takes in the array, the current index, and the target item as its parameters. Within the function, you can use a base case to check if the current index is greater than or equal to the length of the array, and if so, return "Item not found." Otherwise, you can check if the current item at the index is equal to the target item, and if so, return the current item. If the current item is not equal to the target item, you can call the function again with the next index and return the result.

Here is a simple function:

function recursiveSearch(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === target.id) {
            return arr[i];
        }
        if (arr[i].children) {
            const result = recursiveSearch(arr[i].children, target);
            if (result) {
                return result;
            }
        }
    }
    return null;
}

const data = [
    { id: 1, name: "Rahul", children: [
        { id: 2, name: "Ravi" },
        { id: 3, name: "Anurag", children: [
            { id: 4, name: "Rohit" },
            { id: 5, name: "Rakhi" }
        ] }
    ] },
    { id: 6, name: "Bob" }
];

const result = recursiveSearch(data, {id: 4, name: "Rohit"});
console.log(result);
// Output: { id: 4, name: "Rohit" }

In this example, the recursiveSearch function takes in an array of nested objects and a target object to search for. The function uses a for loop to iterate over the top-level array, checking if the current object's id matches the target id. If there's a match, it returns the current object. If not, it checks if the current object has a children property and if it does, it calls the recursiveSearch function again, passing in the current object's children array and the target object. This process continues recursively until the target object is found or all the objects have been checked.

 

Summary

In summary, recursive search is a technique for traversing an array of objects and returning a new array containing only the elements that match a specific condition. It can be implemented in JavaScript using a function that takes an array and a condition, and recursively calls itself with the remaining elements in the array until it has searched the entire array. This is a powerful tool for filtering and manipulating data, and can be helpful in many different contexts where you need to extract specific information from a complex data structure.

 

References

Recursion - MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)
Recursion (computer science) - Wikipedia

 

Views: 15

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on LinkedIn.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment