0

i want to make all arrays in one array during a loop , example :

i have array of objects

[{1 ,2,3},{4,5,6}]

used function to convert each object to array [1 ,2,3] [4,5,6]

how i can merge both of this array to be one array [1,2,3,4,5,6]

and this is my code


  const [start, setStart] = useState<Date[]>([]);


  useEffect(() => {
    publicHoliday?.map((holiday) => {
      const eventStartDate = holiday.startDate;
      const eventEndDate = holiday.endDate;

      const holidayDates = enumerateDaysBetweenDates(eventStartDate, eventEndDate);

     //holidayDates is array 


//give me error here "  Type 'Date | Date[]' is not assignable to type 'Date'.
  Type 'Date[]' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 37 more.ts(2322)"

      setStart([...start, holidayDates]);
      return;
    });
  }, [publicHoliday]);
1
  • [{1 ,2,3},{4,5,6}] is not an array. Commented Aug 25, 2021 at 18:56

2 Answers 2

3

Try this one.

 useEffect(() => {
     updatedData = []
     publicHoliday?.forEach((holiday) => {
        ...
        updatedData = [...updatedData, ...holidayDates]
        ...
     })
     setStart(updatedData)
     ...
     

This is the simplified the merge logic.

var updated = []
// origin = [[1,2,3], [4,5,6]]
origin.forEach( (item, index) => updated = [...updated, ...item]) 
// updated = [1,2,3,4,5,6]
Sign up to request clarification or add additional context in comments.

2 Comments

thanks , working but the now start array like this [ Array,Array,Array] , how to make it one array
origin.forEach( (item, index) => updated = [...updated, ...item]) Here origin is [Array, Array...], and updated is the result you are looking for.
0

It appears that this function enumerateDaysBetweenDates is returning Date | Date[] which is what the error eventually tells.

You should first see if you can adjust that method to always return Date[] so that its clear.

If you can't, then you must verify on the calling side, if it's an array or not and proceed accordingly,

if(Array.isArray(holidayDates)){
  setStart([...start, ...holidayDates]);
}
else{
  setStart([...start, holidayDates]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.