reactjsfiltersplitarray.prototype.map

Want to filter and map an array with an id


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

Solution

  • 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)))
    }