Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading