I'm writing a function and this is the last piece of the puzzle, which I thought would be easy to deal with, but after some unsuccessful tinkering with for and while loops, I tried looking it up online and still couldn't find an answer. I came across some obscure and complex solutions, but I think there should be a more straightforward way to solve this. For example, if I have an array
[1, 2, 3, 5, 7, 9]
And the argument is 10, the function should return 6 (1 2 3), because the sum of the values should be <= 10 (or whatever number is passed). If the argument is 4, the function should return 3 (1 2) and so on.
CodePudding user response:
You can use a for
loop:
const arg = 10
const arr = [1, 2, 3, 5, 7, 9]
let res = 0;
const calc = (arr, limit) => {
for (num of arr) {
if (num res > limit) {
break;
}
res = num;
}
return res;
}
console.log(calc(arr, arg))
CodePudding user response:
.reduce()
each current value (cur
) added to the accumulator (acc
) and checked vs. the limit (max
). If acc cur
is less than limit then return acc cur
, otherwise return acc
. Added .sort()
if the array happens to be out of order, as per Spectric's comment.
const array = [1,2,3,5,6,8];
const mixed = [0,7,3,8,2,1];
const A = 10;
const B = 15;
const closest = (arr, max) => {
return arr.sort((a, b) => a - b).reduce((acc, cur) =>
(acc cur) > max ? acc : (acc cur));
}
console.log(closest(array, A));
console.log(closest(array, B));
console.log(closest(mixed, B));