Home > database >  Compare Two different arrays and update array of objects with useState in React
Compare Two different arrays and update array of objects with useState in React

Time:04-09

So I have an array called preferredMeetingDays:

const preferredMeetingDays = ["Mon", "Tue"];

I have an array of days called chosenDays:

const chosenDays = [
  {
    id: "Sun",
    dayValue: "Sun",
    chosen: false
  },
  {
    id: "Mon",
    dayValue: "Mon",
    chosen: false
  },
  {
    id: "Tue",
    dayValue: "Tue",
    chosen: false
  },
  {
    id: "Wed",
    dayValue: "Wed",
    chosen: false
  },
  {
    id: "Thu",
    dayValue: "Thu",
    chosen: false
  },
  {
    id: "Fri",
    dayValue: "Fri",
    chosen: false
  },
  {
    id: "Sat",
    dayValue: "Sat",
    chosen: false
  }
]

The chosenDays array is used with useState like:

const [isChosenDays, setIsChosenDays] = useState(chosenDays);

What I want to do is compare the preferredMeetingDays array with the isChosenDays state and change the chosen key value of a single day object to true if the day object in isChosenDays is present in preferredMeetingDays array. In this case, that would be "Mon" and "Tue". The new isChosenDays state would be:

[
  {
    id: "Sun",
    dayValue: "Sun",
    chosen: false
  },
  {
    id: "Mon",
    dayValue: "Mon",
    chosen: true
  },
  {
    id: "Tue",
    dayValue: "Tue",
    chosen: true
  },
  {
    id: "Wed",
    dayValue: "Wed",
    chosen: false
  },
  {
    id: "Thu",
    dayValue: "Thu",
    chosen: false
  },
  {
    id: "Fri",
    dayValue: "Fri",
    chosen: false
  },
  {
    id: "Sat",
    dayValue: "Sat",
    chosen: false
  }
]

I have tried this code but it is not working and adding undefined to the array:

useEffect(() => {
    if(preferredMeetingDays.length > 0) {
      setIsChosenDays(isChosenDays => [
        ...isChosenDays,
        ...preferredMeetingDays.map((preferredDay) => {
          isChosenDays.map(chosenDay => {
            if(chosenDay.id === preferredDay) {
              return {
                ...chosenDay,
                chosen: true
              }
            }
            return chosenDay;
          })
        }),
      ])
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

How do I get this to work? Thank you in advance.

CodePudding user response:

useEffect(() => {
    setIsChosenDays(
      isChosenDays.map((day) => {
        if (preferredMeetingDays.some((pDay) => pDay === day.id)) {
          day.chosen = true;
          return day;
        } 
        return day;
        
      })
    );
  }, []);

here is a working example codesandbox

  • Related