Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda