I'm currently tackling a challenge that requires me to obtain a specific number using a given 3D array. This array consists of 2D arrays, each containing the same number repeated x times. The parent array is sorted from largest to smallest.
Here's an example of the parent array;
array = [
[5, 5, 5, 5, 5, 5],
[4, 4, 4],
[3, 3, 3, 3],
[1, 1, 1, 1, 1, 1, 1],
];
The target number I need to achieve is 27;
let number = 0;
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array[i].length; j++){
number += array[i][j]
}
}
The current for loop adds up all the numbers in the parent array, but I want it to stop iterating when it exceeds 27 and precisely hit the number 27.
In the example given above, during the first iteration, it should continue until it reaches 25 and then move on to the second iteration; the second and third iterations are skipped because the sum must be exactly 27; finally, it breaks during the second run of the fourth iteration when the total becomes 27;
I apologize for this verbose explanation, my understanding of JavaScript is limited so I tried my best to articulate it clearly.