Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

145
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda