Don’t use array methods in that case, use a loop: iteration methods like reduce go through the entire array. The reduce callback tracks the index (that’s the third argument), so you can just add 0 if the index is > 4, but you’re still going through the entire array (when you really want to stop iterating at that point).
I haven’t tried this, but it seems like if you filtered the array first, or used slice, you could use reduce after that. Avoiding loops seems like a good thing.
You’re still looping, but doing it that way you’d be doing it multiple times over the same array. Computers are plenty fast, so this isn’t really much of an issue, but to do it in one pass is much easier using an imperative loop, and generally clearer. Examples using single iteration method:
Hi @dhill94.
If you are still in the beginning phase of learning to program, i think it’s better if you didn’t use the reduce method first.
It helps if you focus your learning on the basic construct that exist in all programming language first:
conditional statement, function, basic data structure like array, and loop.
In this particular problem, it boils down to accessing element of the array from the lowest index up to a certain index that you want and then add each of that element you are accessing to a variable. That means that you need two variable:
One for keeping track of the index that you use to access the element
One for accumulating element that you access.
That means you can use the first variable that stores the index to check if the index of the element that you are accessing now is equal to index limit that you want.
var arr = new Array(1, 2, 3, 4, 5);
var total = 0;
for (var x = 0; x < arr.length; x++){
total += 1
// use this if you have to stop at index 4
/*
if(x == 4) {
break
}
*/
}
console.log(total)