ckhedda
ckhedda

Reputation: 73

How to summize every second number in an Array?

I'm having trouble summize every second/other number in an Array in Javascript. Any suggestions? (Using Norwegian functions, sorry for that!) Such as: 2, 4, 6, 8, 10 = 30..

My function for the second/other number is

function tall(nummer) {
var tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

if (nummer == 5) {
    partall = tall.filter((_,i) => i&1);
        document.getElementById("tall").innerHTML = partall;
}

and for the final sum:

if (nummer == 9) {
    partall = tall.filter((_,i) => i&1);
    partall += tall;
        document.getElementById("tall").innerHTML = partall;
}

Upvotes: 2

Views: 1253

Answers (3)

Rafael
Rafael

Reputation: 7746

Array.prototype.reduce is certainly the way to go here:

var sum = [0,1,2,3,4,5,6,7,8,9,10].reduce((sum, n, i) => {
    if (i % 2 === 0)
        sum += n;
    return sum;
}, 0);

console.log(sum);

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1075925

The simplest way I can see is to use reduce (good for summing) and just don't add in the values for the indexes you don't want to contribute to the sum:

const tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const sum = tall.reduce((sum, val, i) => sum + (i & 1 ? val : 0), 0);
console.log(sum);

or

const tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const sum = tall.reduce((sum, val, i) => (i & 1 ? sum + val : sum), 0);
console.log(sum);

Upvotes: 4

Willem van der Veen
Willem van der Veen

Reputation: 36680

Try the following:

var tall = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
let sum = 0;

for (let i = 0; i < tall.length; i +=  2){
  sum += tall[i];
}

console.log(sum)

Instead of loop over all the number you increment i by 2 thus only looping over the odd numbers.

Upvotes: 4

Related Questions