Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix an error when working with an array and the find method?

I have a question about working with the find method. I have a task – I need to go through the array and find a match with a specific string. But at the same time there is a condition that this string can be inside one of the objects already in its child array. I make an if construct in my function to check this when passing through the array, but it does not work out as I expected. Tell me, please, where I went wrong.

P.S. I write more correctly. If the array object "newList" has "items" , then you need to look for comparison not in the object, but in its "items" array among "role" . If "items" does not exist for the object, then we look for a match in this object among "role"

const newList = [
    {
        role: "role111",
        title: "title1",
    },
    {
        role: "role222",
        title: "title2",
    },
    {
        role: "role333",
        title: "title3",
    },
    {
        role: "role444",
        title: "title4",
        items: [{
            role: "role555",
            title: "title5",
        }, {
            role: "role666",
            title: "title6",
        }, {
            role: "role777",
            title: "title7",
        },]
    },
    {
        role: "role888",
        title: "title8",
    },
];

const url = "role7";


export const findAfterRefresh = (list, url) =>
    list.find((item) => {
        if (item.items && item.items?.length > 0) {
            return item.items.find((childrenITem) => childrenITem.role.includes(url));
        }
        return item.role.includes(url);
    });
;


findAfterRefresh(newList, url);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your solution was close, but if you call find on newList, it can only ever return one of the elements of newList, it can’t return an element from the items array of one of those elements. That plus the fact you want the role value, not the element itself, makes the find method not a good match for your current data structure (but keep reading; if you really want to use find, there’s a way).

Instead, a simple loop with recursion does the job:

/*export*/ const findAfterRefresh = (list, url) => {
    for (const item of list) {
        if (item.role?.includes(url)) {
            return item.role;
        }
        if (item.items?.length) {
            const childRole = findAfterRefresh(item.items, url);
            if (childRole) {
                return childRole;
            }
        }
    }
};

Here’s a version with explanatory comments:

/*export*/ const findAfterRefresh = (list, url) => {
    // Loop the given list...
    for (const item of list) {
        // ...check this item's role
        // (Remove   v-- this `?` if `role` will always be there)
        if (item.role?.includes(url)) {
            return item.role;
        }
        // If this item has child items, check them
        if (item.items?.length) {
            // Search child items using recursion
            const childRole = findAfterRefresh(item.items, url);
            if (childRole) {
                // Found it, return it
                return childRole;
            }
            // Didn't find it, keep looping
        }
    }
};

Live Example:

const newList = [
    {
        role: "role1",
        title: "title1",
    },
    {
        role: "role2",
        title: "title2",
    },
    {
        role: "role3",
        title: "title3",
    },
    {
        role: "role4",
        title: "title4",
        items: [
            {
                role: "role5",
                title: "title5",
            },
            {
                role: "role6",
                title: "title6",
            },
            {
                role: "role7plusotherstuff",
                title: "title7",
            },
        ],
    },
];

/*export*/ const findAfterRefresh = (list, url) => {
    // Loop the given list...
    for (const item of list) {
        // ...check this item's role
        // (Remove   v-- this `?` if `role` will always be there)
        if (item.role?.includes(url)) {
            return item.role;
        }
        // If this item has child items, check them
        if (item.items?.length) {
            // Search child items using recursion
            const childRole = findAfterRefresh(item.items, url);
            if (childRole) {
                // Found it, return it
                return childRole;
            }
            // Didn't find it, keep looping
        }
    }
};

console.log("Searching for 'role7'");
console.log(findAfterRefresh(newList, "role7"));
console.log("Searching for 'role2'");
console.log(findAfterRefresh(newList, "role2"));

Note: I added a bit to the role containing role7 so you could see that the code returns the full role, not just the bit in url.


But if you really want to use find, you can do it by first creating a flat array of roles:

// Creates a new array of `role` values (the array may also contain
// `undefined`, if the `role` property of any element or child element is
// `undefined`)
const flattenRoles = (list) =>
    (list ?? []).flatMap((item) => [item.role, ...flattenRoles(item.items)]);

/*export*/ const findAfterRefresh = (list, url) => {
    return flattenRoles(list).find((role) => role?.includes(url));
};

That code’s a big shorter, but note that it creates a number of temporary arrays, and it always works its way through the full list before looking for roles, whereas the earlier version stops looking as soon as it’s found a matching role. That’s unlikely to be a problem if newList is of a reasonable size, but it’s worth keeping in mind. (I’d probably use the earlier version, not this.)

Here’s that in action:

const newList = [
    {
        role: "role1",
        title: "title1",
    },
    {
        role: "role2",
        title: "title2",
    },
    {
        role: "role3",
        title: "title3",
    },
    {
        role: "role4",
        title: "title4",
        items: [
            {
                role: "role5",
                title: "title5",
            },
            {
                role: "role6",
                title: "title6",
            },
            {
                role: "role7plusotherstuff",
                title: "title7",
            },
        ],
    },
];

// Creates a new array of `role` values (the array may also contain
// `undefined`, if the `role` property of any element or child element is
// `undefined`)
const flattenRoles = (list) =>
    (list ?? []).flatMap((item) => [item.role, ...flattenRoles(item.items)]);

/*export*/ const findAfterRefresh = (list, url) => {
    return flattenRoles(list).find((role) => role?.includes(url));
};

console.log("Searching for 'role7'");
console.log(findAfterRefresh(newList, "role7"));
console.log("Searching for 'role2'");
console.log(findAfterRefresh(newList, "role2"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading