0

I have an array of elements, i need to add the every first, seven, thirteen and nineteen (70, 74, 50, 70) values and sum of them using java script.

var rowSpanHeight = ['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70'];

Anyone can help? Thanks!

Medoju Narendar
  • 185
  • 1
  • 4
  • 18

4 Answers4

2

I assume from your question that you have to add them whenever they change in the array, in that case you can use:

function sumIfDifferent( inputArr ) {
    var lastNum = -1;
    var total = 0;
    for (var i = 0, l = inputArr.length; i < l; i++) {
        num = parseInt(inputArr[i], 10);
        if (num != lastNum) {
            lastNum = num;
            total+=num;
        }
    }
    return total;
}

alert(sumIfDifferent(['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70']));
Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40
1

Simply add them up:

var rowSpanHeight = ['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70'];
document.write(parseInt(rowSpanHeight[0]) + parseInt(rowSpanHeight[6]) + parseInt(rowSpanHeight[12]) + parseInt(rowSpanHeight[18]));
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

a simple approach would be -

  var rowSpanHeight = ['70', '70', '70', '70', '70', '70','74', '74', '74', '74', '74', '74','50', '50', '50', '50', '50', '50','70', '70', '70', '70', '70', '70'];
    var sum = ~~rowSpanHeight [0] + ~~rowSpanHeight [6] + ~~rowSpanHeight [12] + ~~rowSpanHeight [18];
    console.log(sum);

note: the use of ~~ (double tilde) here is a quick way to convert the string to a number, had the string been 12.12 this would not have been used as ~~ will remove everything after a decimal place (much like parseInt). more info in SO questions like https://stackoverflow.com/a/10841248/2737978

Community
  • 1
  • 1
Quince
  • 14,790
  • 6
  • 60
  • 69
  • dude....... double bitwise nots for someone who doesn't understand how to access an array element by index? ;) – p e p Nov 07 '14 at 15:34
  • yep i was just going to edit it then saw someone else had already posted the same with parseInt so figured would leave it as another option – Quince Nov 07 '14 at 15:35
  • Totally kidding by the way. – p e p Nov 07 '14 at 15:36
  • nah it's what i though after i posted it and saw I started the answer with the phrase 'simple approach' :) – Quince Nov 07 '14 at 15:38
0

something like this might work ...

var sum=0;
for(var a in rowSpanHeight){
    switch(a){
        case 0:
        case 6:
        case 12:
        case 18:
             sum+=parseInt(rowSpanHeight[a]);
        break;
    }
}
Adam MacDonald
  • 1,958
  • 15
  • 19