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.
JavaScript
x
12
12
1
const
2
array1 = ['A', 'A', 'B', 'B', 'C', 'C', 'A', 'C'],
3
array2 = ['a', 'aa', 'b', 'bb', 'c', 'cc', 'aaa', 'ccc'],
4
array3 = [1, 2, 3, 4, 5, 6, 7, 8],
5
values = [array2, array3],
6
result = Object.values(array1.reduce((r, v, i) => {
7
r[v] ??= [v];
8
r[v].push(values.map(a => a[i]));
9
return r;
10
}, {}));
11
12
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }