3
In Javascript, I, using in this case the for loop common iteration of array with the variable i, I am trying to create an arrangement with sub-arrangements that have data from other arrangements from an order relative to the position of i.
This code example describes situation:
var arranjoBase1 = ["a", "b", "c", "d", "e"]
var arranjoBase2 = ["f", "g", "h", "i", "j"]
var arranjoBase3 = [1, 2, 3, 4, 5]
var arranjoFinal = [ [], [], [], [], [] ]
for(i = 0; i < arranjoFinal.length; i++)
{ arranjoFinal[i].push(arranjoBase1[i], arranjoBase2[i], arranjoBase3[i]);
if(i != 0) { arranjoFinal[i].push(arranjoBase3[i - 1]) }
else { arranjoFinal[i].push(arranjoBase3[arranjoBase3.length - 1]) };
if(i != arranjoBase3.length - 1) { arranjoFinal[i].push(arranjoBase3[i + 1]) }
else { arranjoFinal[i].push(arranjoBase3[0]) };
if(i == 0) { arranjoFinal[i].push(arranjoBase3[arranjoBase3.length - 2]) }
else if(i == 1) { arranjoFinal[i].push(arranjoBase3[arranjoBase3.length - 1 ]) }
else { arranjoFinal[i].push(arranjoBase3[i - 2]) };
if(i == arranjoBase3.length - 1) { arranjoFinal[i].push(arranjoBase3[1]) }
else if(i == arranjoBase3.length - 2) { arranjoFinal[i].push(arranjoBase3[0]) }
else { arranjoFinal[i].push(arranjoBase3[i + 2]) } };
//Resultado Final
var arranjoFinal = (5) [Array(7), Array(7), Array(7), Array(7), Array(7)]
//Exemplo de Arranjo Final
var arranjoFinal[0] = (7) ["a", "f", 1, 5, 2, 4, 3]
This code already gives me the desired results.
The point is, I needed to use a lot of conditionals if to circumvent the problem of whether the result of one of the arithmetic operations to find the next element to be added to the Final arrangement is outside the index of the Base3 arrangement - in which case it would be returned Undefined in place of the desired element -, I feel that there must be a much more practical solution to achieve this result, which, for example, is also sustainable for arrangements greater than five elements.
So, is there really a more [practical/concise] way to achieve results like this? As, for example and preferably, a way of saying that if the result of an arithmetic operation to find the element index of a array exceed the content of that array this means that it is for her to continue the operation from her [beginning/end]?
Could you explain in more detail what the code should do or does today? if possible as if it were the explanation given to some developer who would develop this task for you. This way a possible solution will arise quite different from yours and may be better.
– Paulo Roberto Rosa