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?
CodePudding user response:
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.
CodePudding user response:
You just need to polish up on your algorithm skills
const list1 = [{
checked: false,
title: "Fully Furnished"
}, {
checked: false,
title: "Swimming Pool"
}, {
checked: false,
title: "En suite Rooms"
}];
const list2 = ["Fully Furnished", "Swimming Pool"];
list2.forEach((item => {
let index = list1.findIndex(looky => looky.title == item);
if (index != undefined) {
list1[index].checked = true;
}
}));
console.log(list1);