Grouping elements from two arrays to one element of another array [closed]

I have three arrays that I need to link to each other in this way:

  1. arr1 = [‘A’, ‘A, ‘B’, ‘B’ ‘C’, ‘C’, ‘A’, ‘C’]
  2. arr2 = [‘a’, ‘aa’, ‘b’, ‘bb’, ‘c’,’cc’, ‘aaa’, ‘ccc’]
  3. arr3 = [1, 2, 3, 4, 5, 6, 7, 8]

I want these arrays to be linked like this: [[‘A’, [‘a’, 1], [‘aa’,2], [‘aaa’, 7]], [‘B’, [‘b’, 3], [‘bb’,4]], [‘C’, [‘c’, 5], [‘cc’,6], [‘ccc’,8]]]

Any suggestions on how to go about with structuring this array?

Answer

You could group by the first array.

const
    array1 = ['A', 'A', 'B', 'B', 'C', 'C', 'A', 'C'],
    array2 = ['a', 'aa', 'b', 'bb', 'c', 'cc', 'aaa', 'ccc'],
    array3 = [1, 2, 3, 4, 5, 6, 7, 8],
    values = [array2, array3],
    result = Object.values(array1.reduce((r, v, i) => {
        r[v] ??= [v];
        r[v].push(values.map(a => a[i]));
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Leave a Reply

Your email address will not be published. Required fields are marked *