Rahul
Rahul

Reputation: 25

How to filter values of an array inside an array?

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

Upvotes: 1

Views: 62

Answers (1)

Airthee
Airthee

Reputation: 11

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);

Upvotes: 1

Related Questions