Transform array to the following format

I have an array of objects that have 2 fields key and type, the type field is practice or theory

Result:

  1. group the array by key

  2. transform the array: in the new array the object with type practice should come in the even index and object with type theory should be in the odd index. (check the input and the output if my explanation wasn’t clear)

here’s my code but it doesn’t work as expected in the transform the array

function transformArray(arr) {
  const grouped = arr.reduce((result, item) => {
    const key = item.key;
    if (!result[key]) {
      result[key] = { key, values: [] };
    }
    result[key].values.push(item);
    return result;
  }, {});

  for (const group in grouped) {
    const values = grouped[group].values;
    const newValues = [];
    for (let i = 0; i < values.length; i++) {
      const item = values[i];
      if (item.type === 'practice' && i % 2 === 0) {
        newValues.push(item);
      } else if (item.type === 'theory' && i % 2 === 1) {
        newValues.push(item);
      }
    }
    grouped[group].values = newValues;
  }

  return Object.values(grouped);
}

example input:

const input = [
{ key: 'A', type: 'practice' },
{ key: 'A', type: 'practice' },
{ key: 'A', type: 'theory' },
{ key: 'A', type: 'theory' },

{ key: 'B', type: 'practice' },
{ key: 'B', type: 'theory' },
{ key: 'B', type: 'practice' },

{ key: 'C', type: 'practice' },
{ key: 'C', type: 'theory' },
{ key: 'C', type: 'practice' },
]

output

[
  {
    key: 'A',
    values: [
      { key: 'A', type: 'practice'},  // index = even ==> practice
      { key: 'A', type: 'theory' },    // index = odd ==> theory
      { key: 'A', type: 'practice'}, // index = even ==> practice
      { key: 'A', type: 'theory'}, // index = odd ==> theory
    ],
  },
  {
    key: 'B',
    values: [
      { key: 'B', type: 'practice' },
      { key: 'B', type: 'theory',},
      { key: 'B', type: 'practice' },
    ],
  },
  {
    key: 'C',
    values: [
      { key: 'C', type: 'practice' },
      { key: 'C', type: 'theory', },
      { key: 'C', type: 'practice'},
    ],
  },
]