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

205
Views
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 answers
Answer question

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