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?
CodePudding user response:
As you're after the index, you could look at using the array method .findIndex()
. The below code adds to sum
for each item in arr
, and then checks whether the new accumulate sum
value is greater than or equal to the limit. If it is, the callback for findIndex will return true, giving you the index. If the callback function to findIndex doesn't find any values, it will result in -1
, which you can then check before you return to see if you need to return the array length or the actual index:
const findIndex = (arr, limit) => {
let sum = 0;
const idx = arr.findIndex((num, idx) => (sum =num) >= limit);
return idx > 0 ? idx : arr.length;
}
console.log(findIndex([1,2,1,3,4,1,2], 5));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Since you need the
1) index
upto which the sum
is greater or equal to limit
2) You want to return
early as soon as the sum exceeds limit
then you should go for old school for
loop. There is no need to accumulate the index
and value
using nums.entries()
function findIndex(nums, limit) {
let sum = 0;
for (let i = 0; i < nums.length; i) {
sum = nums[i];
if (sum >= limit) return i;
}
// Return something explicitely to
// indicate that sum can't exceeds limit.
// You may return -1 if you like
}
console.log(findIndex([1, 2, 1, 3, 4, 1, 2], 5));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>