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

211
Visualizações
Splitting, comparing and outputting the most appropriate value in the array

I have a function that splits one large array into a target chunks.

function chunkArray(ls, k, t) {
 let outputArr = [];
 for (let i = 0; i < ls.length; i += k) {
    outputArr.push(ls.slice(i, k + i));
 }
 return  outputArr;
}

I need to modify the function so that it first sums each output array, and then compares the result to the target and outputs the sum of the array whose is close to the target.

const ls = [51, 56, 58, 59, 61, 63, 68, 70, 72];
chunkArray(ls, 3, 182);
=> arr1 = [51, 56, 58]; => 165
=> arr2 = [59, 61, 63]; => 183 
=> arr3 = [68, 70, 72]; => 210
=> 183

Please, advise how to correctly design the logic and which methods are most suitable for this task.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could take a sum for each wanted k elements and compare the absolute delta of last and actual sum.

function chunkArray(ls, k, t) {
    let result = 0,
        i = 0;

    while (i < ls.length) {
        let sub = 0;
        for (let j = 0; j < k; j++) sub += ls[i + j] || 0;
        if (Math.abs(result - t) >  Math.abs(sub - t)) result = sub;
        i += k;
    }
    
    return result;
}

const ls = [51, 56, 58, 59, 61, 63, 68, 70, 72];
console.log(chunkArray(ls, 3, 182)); // 183

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