I have three arrays that I need to link to each other in this way:
- arr1 = [‘A’, ‘A, ‘B’, ‘B’ ‘C’, ‘C’, ‘A’, ‘C’]
- arr2 = [‘a’, ‘aa’, ‘b’, ‘bb’, ‘c’,’cc’, ‘aaa’, ‘ccc’]
- 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]]]
How can I create this new array? N.B The elements are pushed sequentially so arr1[0] links to arr2[0], arr1[1] links to arr2[1]
Advertisement
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; }