Help with Arrays?!

Hi everyone,
I’m new to JavaScript so still trying to get my head around a lot of things!

Just wondering if someone might be able to help me with something.
I’ve used .reduce to get the total value of some numbers.

let initialValue = 0;
let totalPoints = [3, 3, 1, 1, 3, 1, 1, 3];

let sum = totalPoints.reduce((totalValue, currentValue) => {
console.log(`Total Value: ${totalValue}, Current Value: ${currentValue}`)
 return totalValue + currentValue }, initialValue);

If I wanted to add up the elements in the array but stop at the 4th element in the index, what would be the easiest way to do this?


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

1 Like

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

1 Like

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:

totalPoints.flatMap((v, i) => i > 4 ? [] : [v])
totalPoints.reduce((acc, v, i) => acc + (i > 4 : 0 : v), 0)

With slice:

totalPoints.slice(0, 4).reduce((acc, v) => acc + v, 0)


function sumN (nums, n) {
  let total = 0;
  for (let i = 0; i < n; i++) {
    total += nums[i];
  return total;

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.

1 Like

It is good to do it via a loop

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) {


this is not valid javascript

Fixed it, Thank you !!

that sounds like a smart solution while still sticking to the reduce method! :slight_smile: