I am trying to update an array based on another array. For example, if Array 2 contains the word "Fully Furnished", I would like to update Array1 Fully Furnished ‘checked’ to true.
const [Array1,
setArray1] = useState([
{
checked: false,
title: "Fully Furnished"
}, {
checked: false,
title: "Swimming Pool"
}, {
checked: false,
title: "En suite Rooms"
}
]);
const Array2= ["Fully Furnished", "Swimming Pool"];
This is what I have been trying so far, but it only updates the first row.
useEffect(() => {
for (let i = 0; i < Array2.length; i++) {
setArray1(
Array1.map((item, i) =>
item.title === Array2[i] && item.checked === false
? { ...item, checked: true }
: item
))
}
}, []);
How do I solve this?
>Solution :
const array3=Array1.map(function (item) {
if (Array2.includes(item.title)) {
item.checked = true;
}
return item;
})
setArray1(array3)
You may try this inside useEffect function.