I have two arrays with ids
that have linked lengths. By linked lengths I mean that if ArrayA
has length = 4
then ArrayB
will have the length
equal with (ArrayA.length * (ArrayA.length - 1)) / 2
(which means if ArrayA
has length = 4
then ArrayB length = 6
, if ArrayA
has length = 5
then ArrayB length = 10
and so on).
So let's say these are my arrays: ArrayA = [1, 2, 3, 4]
and ArrayB = [a, b, c, d, e, f]
.
I have to create a new array of arrays
based on the next logic:
In the end the new array should look as it follows, where the second parameter is a value from the first array and the third parameter is a value from the second array:
[
[uuidv4(), 1, a],
[uuidv4(), 2, a],
[uuidv4(), 1, b],
[uuidv4(), 3, b],
[uuidv4(), 1, c],
[uuidv4(), 4, c],
[uuidv4(), 2, d],
[uuidv4(), 3, d],
[uuidv4(), 2, e],
[uuidv4(), 4, e],
[uuidv4(), 3, f],
[uuidv4(), 4, f]
]
In the end, I should return this kind of array no matter the size of the arrays, but the arrays have some kind of linked length.
I can't do this with a simple mapping because I don't know how to achieve this kind of logic.
The base idea is that ArrayA
is an array of team ids and ArrayB
is an array of match ids and I need to add two teams id for every match id.
Thank you for your time! If something is unclear, I'll try to explain better.
CodePudding user response:
As I have seen in your image the logic is for each element in the largest array, assign 2 elements from the shortest one without duplication. In order to achieve this the idea is to loop the largest array and assign in a new array the elements of the shortest array using 2 different index (xIndex0, xIndex1).
In the example below you can see how xIndex0 is pointing to the first element to add from the shortest array, and xIndex1 is pointing to the second element to add, we are incrementing those index depending if we have already reached the end of the shortest array.
var x = [1, 2, 3, 4]
var xIndex0 = 0
var xIndex1 = xIndex0 1
var y = ["a", "b", "c", "d", "e", "f"]
var result = [];
y.forEach((elem,index) => {
result.push([null, x[xIndex0], elem]); //replace null with everything you need
result.push([null, x[xIndex1], elem]);
xIndex1 ;
if(xIndex1 > x.length-1)
{
xIndex0 ;
xIndex1 = xIndex0 1
}
})
console.log(result);