Function to add and subtract alternate array elements in JavaScript

Took 5 minutes and 10 seconds to code JavaScript method to add and subtract alternate elements in an array. Here is the code snippet.

Code:

arr = [1,2,3,4,5,6,7];
function alternateAddSubtract(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
sum += arr[i];
} else {
sum -= arr[i];
}
}
return sum;
}

document.write(alternateAddSubtract(arr));

Result:

4

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...