简体   繁体   中英

Check if two array are equal and disable a button of array that have same value

I'am rendering cards and i have two array, i would like to disable the buttons that have an equal id between the two array.

for expemple:

idOne = [9,5,1,4];
idTwo = [6,1,3,4];

In this case i would like to disable the button for 4 and 1 since both have the same value.

here is the render method where i pass the button

render(){
this.button()
}

Here is my try

button = () {
idOne = [9,5,1,4];
idTwo = [6,1,3,4];

const checkId = idOne.some(n => idTwo.includes(n))
if(checkedId){
return <Button disable />
} 

return <Button />
}
}

But this will disable all the buttons and not the ones that have equal id's.

thanks for the help

I broke it down into two seperate steps. First I would use filter to return an array of all the ids that match between the two ids.

const arr1 = [9, 5, 1, 4]
const arr2 = [6, 1, 3, 4]
const matches = arr1.filter(el => arr2.includes(el)

Then once I have an array of all the matches you can map over all the ids in arr1 and then do the check if any ids sync up. This will return a bool value that will allow you to render conditional components

return arr1.map(el => {
   if (matches.includes(el)) {
       return <Button disable />
   }

   return <Button />
})

You could refactor it down even smaller to 1 step if you wanted by chaining the filter and the map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM