I have an array of numbers and some limit.
const a = [1,2,1,3,4,1,2];
const limit = 5;
What's the most javascripty way of reducing this array to the index such that the sum from the beginning to the index would exceed the limit
?
I've done
function findIndex(nums, limit) {
let s = 0;
for (let [index, num] of nums.entries()) {
s += num;
if (s >= limit) {
return index;
}
}
return nums.length;
}
findIndex([1,2,1,3,4,1,2], 5)
3
Is there a more neat way of doing this using reduce
or something else?