Find an element in an array recursively

后端 未结 3 1336
情深已故
情深已故 2021-01-04 05:55

I have an array of objects. Every object in the array has an id and an item property that is an array containing other object. I need to be able to find an element in an arr

3条回答
  •  孤街浪徒
    2021-01-04 06:34

    I know its late but here is a more generic approach

    Array.prototype.findRecursive = function(predicate, childrenPropertyName){
        if(!childrenPropertyName){
            throw "findRecursive requires parameter `childrenPropertyName`";
        }
        let array = [];
        array = this;
        let initialFind =  array.find(predicate);
        let elementsWithChildren  = array.filter(x=>x[childrenPropertyName]);
        if(initialFind){
            return initialFind;
        }else if(elementsWithChildren.length){
            let childElements = [];
            elementsWithChildren.forEach(x=>{
                childElements.push(...x[childrenPropertyName]);
            });
            return childElements.findRecursive(predicate, childrenPropertyName);
        }else{
            return undefined;
        }
    }
    

    to use it:

    var array = [];
    var joe = array.findRecursive(x=>x.Name=="Joe", "students");
    

    and if you want filter instead of find

    Array.prototype.filterRecursive = function(predicate, childProperty){
        let filterResults = [];
        let filterAndPushResults = (arrayToFilter)=>{
            let elementsWithChildren  = arrayToFilter.filter(x=>x[childProperty]);
            let filtered = arrayToFilter.filter(predicate);
            filterResults.push(...filtered);
            if(elementsWithChildren.length){
                let childElements = [];
                elementsWithChildren.forEach(x=>{
                    childElements.push(...x[childProperty]);
                });
                filterAndPushResults(childElements);
            }
        };
        filterAndPushResults(this);
        return filterResults;
    }
    

提交回复
热议问题