skip to Main Content

I’m in little bit confusion in my code. I have an array,

let arr = [{id:"225",name:"jin"},
           {id:"226, 228",name:"villy"},
           {id:"225",name:"lil"},
           {id:"202,236,289",name:"kill"}]

I stored an ID in a variable called testid. I want to filter my array "arr" which holds the "testid". My testid, for example, is 228. So I want this object from the array with the {id:"226, 228", name: "Villy"}. Could you please assist me in resolving this problem? I use map and filter out everything, but there is some confusion.

This is the code that I tried, every time sae result is coming as result for different testid

{this.state.testid && arr && arr.filter((dd) =>(dd.id.split(", ").map((d) => d === this.state.testid))) 

2

Answers


  1. First we can find the index of array then you can reach your data with it

     arr[arr.findIndex(item => item.id === tested)]
    
    Login or Signup to reply.
  2. If you want a single object, you can use find.

    You can create a function that takes the array and the test id, and returns the found object:

    const findTestId = (arr, testId) => {
        return arr.find((i) => i.id.includes(String(testId)))
    }
    

    To get an array with the found objects, you can do the same with filter:

    const filterTestId = (arr, testId) => {
        return arr.filter((i) => i.id.includes(String(testId)))
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search