Home > Software design >  javascript filter returning empty array even if the values exist in array object being searched
javascript filter returning empty array even if the values exist in array object being searched

Time:11-19

I am having difficulty using the javascript filter in a react native project. I need help filtering an array of objects in a typescript react native project The main issue I am having is in the function called onSearchTextChanged specifically the search method which uses a javascript filter

Here's the main code for the screen below

  const renderItem = ({ item }) => (

    <Pressable style={cardUtilities} android_ripple={{ color: "#dddddd" }} onPress={() => onTapItemHandler(item)}>

      <View style={main}>
        <Text style={utilityname}>{item.title}</Text>
        <Text style={utilityDesc}>{item.description}</Text>
      </View>
    </Pressable>
  )

  const onSearchTextChanged = (e) => {
    setSearchQuery(e)
    search()
  }


  const search = () => {
    console.log("inside handleSearchButtonPressed")
    if (!itemListStore) {
      return
    }
    // const text = searchQuery.toLowerCase()
    console.log("inside 100")
    console.log(itemListStore)

    // array of output objects
    const filteredObjs = itemListStore.filter(
      // eslint-disable-next-line array-callback-return
      ({ item }) => {
       (JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
       ( JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())
      })
    console.log("filteredObjs", JSON.stringify(filteredObjs))

    console.log(typeof filteredObjs)
    console.log(filteredObjs.length)


    console.log("inside 400")
    console.log("searchQuery ", searchQuery)

    if (!searchQuery || searchQuery === "") {
      console.log("1")

    } else if (!Array.isArray(filteredObjs) && !filteredObjs.length) {
      console.log("2")

      // set no data flag to true so as to render flatlist conditionally
      setNoData(true)

    } else if (Array.isArray(filteredObjs)) {
      console.log("3")

      setNoData(false)
      setItemListStore(filteredObjs)
    }

  }


  return (
    <SafeAreaView style={container}>
      {/* <Loader loading={loading} /> */}
      <View style={fullContainer}>
        <View style={MAIN_IMG}>
          <Image style={$welcomeLogo} source={Images.appLogo} resizeMode="contain" />
        </View>
        <View style={TOP_143}>

          <TextInput
            style={textInputStyle}
            onChangeText={onSearchTextChanged}
            underlineColorAndroid="transparent"
            placeholder="Search Here"
            value={searchQuery}
          />


        </View>
        <FlatList
          data={itemListStore}
          renderItem={renderItem}
          keyExtractor={() => {
            return uuid.v4()   ""
          }} />
      </View>


    </SafeAreaView>
  )

Here is sample data made up of an array of objects to be filtered

[
   {
      "description":[
         "At company; Professionals, we believe that individuals and organisations need to apply a whole new level of thinking to navigate and thrive in the emerging world. We no longer have the luxury of conducting business as usual. The organisation or individual that will survive in today&rsquo;s world is one who can imagine and create their future.
​
For anyone who feels uneasy and boxed up in their careers, or entrepreneurs and organisations who want to stay ahead of the new era, or youths who want to be equipped for the future - we can help you achieve this."
      ],
      "guid":[
         [
            "Object"
         ]
      ],
      "industry":[
         "Consulting"
      ],
      "link":[
         "https://www.myjobmag.com/jobs/business-development-executive-at-protege-management-2"
      ],
      "pubDate":[
         "Fri, 18 Nov 2022 17:31:56 GMT"
      ],
      "title":[
         "Business Development Executive at Protege Management"
      ]
   },
   {
      "description":[
         "Montaigne Place Is the leading luxury cosmetics, wellbeing and fragrance company in country. We are the hallmark of sophistication, luxury makeup, skincare innovation and sublime fragrances."
      ],
      "guid":[
         [
            "Object"
  ]
      ],
      "industry":[
         "Sales / Retail"
      ],
      "link":[
         "https://www.myjobmag.com/jobs/business-development-manager-female-at-montaigne-ah-limited"
      ],
      "pubDate":[
         "Fri, 18 Nov 2022 17:28:02 GMT"
      ],
      "title":[
         "Job Openings at Montaigne AH Limited"
      ]
   }]

Here are the logs output below using a searchQuery value of business

 LOG  filteredObjs []
 LOG  object
 LOG  0
 LOG  inside 400
 LOG  searchQuery  Business
 LOG  3

CodePudding user response:

I saw two errors

Your code:

    const filteredObjs = itemListStore.filter(

      // here you destructure the row and take item but item doesn't exist in your object 
      ({ item }) => {
// here there is no return       
(JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
       ( JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())
      })

You need to do

    const filteredObjs = itemListStore.filter(
  (item) => {
    return (JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())
  })

CodePudding user response:

Seems like you are missing the return statement in your filter callback function. You have to return the boolean result for it to work

 const filteredObjs = itemListStore.filter(
      // eslint-disable-next-line array-callback-return
      ({ item }) => {
       return (JSON.stringify(item?.description[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (JSON.stringify(item?.title[0]))?.toLowerCase().includes(searchQuery.toLowerCase()) ||
       ( JSON.stringify(item?.link[0]))?.toLowerCase().includes(searchQuery.toLowerCase())
      })
  • Related