score:1

Accepted answer

You start with an array length 5, then group to create an array length 3 (with the nested array inside the 2nd element of this)

Then in your handleUngroupingQuestions function, the first variable filteredByChecked is defined via the filter function as an array with 1 element only (the single element with the nested array questionGroup)

const filteredByChecked: VariableConfig[] = questionAdded.filter(
      (q: VariableConfig) => q.checked === true
    );

Then when you try to ungroup, you are passing the length 3 array to the function, which takes a different index (the second element, index 1):

const extractGroup = (i: number) => {
      console.log(i);
      return filteredByChecked.length ? filteredByChecked[i].questionGroup : [];
    };

The i being passed to extractGroup here is 1, which does not exist as filteredByChecked is a length 1 array.

Please consider this single map function as your ungrouping handler:

const handleUngroupingQuestions = (): void => {
    const extractGroups = (groupedArr: Array) => {
      return groupedArr.flatMap((x) =>
        x.questionGroup.length > 0 ? [...x.questionGroup] : x
      );
    };

    const newQs = extractGroups(questionAdded);
    const sortedQs = newQs.sort((a, b) =>
      parseInt(a.name.slice(-1), 10) > parseInt(b.name.slice(-1), 10) ? 1 : -1
    );

    console.log(sortedQs);
    addQuestion(sortedQs);
  };

Edit TS-React Grouping (forked)


Related Query

More Query from same tag