Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
JavaScript: skipping to the next array in 3d array when if statement fulfilled

I'm currently working on a problem that requires me to get a certain number with a given 3d array. That Array Contains 2D arrays which contain a number x amount of time. Parent array sorted from bigger to smaller.

Example of parent array;

array = [
 [5, 5, 5, 5, 5, 5],
 [4, 4, 4],
 [3, 3, 3, 3],
 [1, 1, 1, 1, 1, 1, 1],
];

and number I want to get 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 for loop above is obviously sums every number in the parent array but I want it to skip the loop when the number passes the 27 and finally break when it is 27.

For the example above, in the first loop, it should run until the number is 25 and skip to the second loop; the second and third loops skip because the number needs to be equal to 27; and finally, the loop breaks in the second run of the fourth loop when the number is 27;

I'm sorry for this long-ass and bloated explanation, my js knowledge is limited I have to try to explain it in words.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

var target = 27; // Or whatever

let number = 0;
let helpers = []

for (let i = 0; number < target && i < array.length; i++){
    helper = []
    for (let j = 0; number < target && j < array[i].length; j++){
        if ( number + array[i][j] <= target ) {
            helper.push(array[i][j])
            if ( ( number += array[i][j] ) == target ) {
                helpers.push(helper)
                helper = []
                console.log( `Found target ${target} at i=${i}, j=${j}` );
                break;
            }
        }
    }
    if (helper.length) {
        helpers.push(helper)
    }
}

console.log(helpers)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!