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

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

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 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