1

I will describe the situation for more clarity. I have an array like this

animalsArray = {
animalID : number,
animalName: string,
animalDescription: string,

animalChild: animalsArray[]

}

Now I have to filter these animals using animalName from user input by textfield. Some animals can have n number of animalChild or non at all or animalChild can have another animalChild inside it.

I already have a code like this

public animalsArray:animalsArray[]

    this.filteredanimalsArray.next(
                this.animalsArray.filter(item => (item.animalName.toLowerCase().indexOf(search) > -1))
            );

To filter the main animalsArray and it works fine but the user input doesn't go through the child arrays.

How can I solve this problem? Thanks in advance

1
  • 1
    Thank you for pointing that out. Will edit the post Commented Sep 9, 2021 at 15:38

1 Answer 1

1

Maybe you could use recursivity like this :

function filterAnimals(animals, name) {
    return animals.filter(animal => {
        const matching = animal.animalName.toLowerCase() === name.toLowerCase();
        const hasChildMatch = Array.isArray(animal.animalChild) && filterAnimals(animal.animalChild, name).length > 0;
        return matching || hasChildMatch;
    });
}

const search = 'leon';
const filterdAnimals = filterAnimals(animalsArray, search);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.