Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating state array based on another array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading