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