Home > other >  How to access an array inside a method?
How to access an array inside a method?

Time:10-20

I need some help. I'm currently doing a search bar feature and I'm using setTimeout() to search only after user stops typing.

Inside setTimeOut() method, I have this array that I need to compare the length and return it.

I want to access filterArray but the console showed undefined.

this.filterArray doesn't work so I'm not sure how to define and access it. Thank you in advance!

This is my code:

        let listArr = this.randomArray() // randomArray() contained list of names

        if (this.searchValue.trim().length > 0) {
            if (this.timeout) {
                this.clear()
            }
        }

       this.timeout = setTimeout(() => {
            const filterArray = listArr.filter((staff) =>
                staff.user.name
                    .toLowerCase()
                    .includes
                    (this.searchValue.trim().toLowerCase()))

                    console.log(this.timeout)
        }, 500)

        if (filterArray.length > 0) {
            listArr = filterArray
        }

        console.log(listArr);
        return listArr 
        // to return a list of names after the search box is empty
    }

CodePudding user response:

Just remove the timeout

        let listArr = this.randomArray() // randomArray() contained list of names

    if (this.searchValue.trim().length > 0) {
        if (this.timeout) {
            this.clear()
        }
    }

   
        const filterArray = listArr.filter((staff) =>
            staff.user.name
                .toLowerCase()
                .includes
                (this.searchValue.trim().toLowerCase()))

                console.log(this.timeout)


    if (filterArray.length > 0) {
        listArr = filterArray
    }

    console.log(listArr);
    return listArr 
    // to return a list of names after the search box is empty
}
  • Related