How to obtain the sum of integers between 2 indexes in the array with JavaScript

The problem is quite simple, given a custom array of numbers of n elements, you should build a function that returns the sum of the numbers between 2 given indexes. For example, with the following array of 5 elements, with the 2 given indexes 0 and 2, the items between those indexes including it, are 1, 2, and 3, its sum is 6:

Sum Integers between some indexes of array in JavaScript


In this case, the solution will be pretty simple and short. To solve this issue, we are going to use the slice function of JavaScript. The slice method of JavaScript returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

The solution is already integrated into JavaScript, the only thing you need to do is to add 1 index to the second provided index to include the item that is not included by default in the slice function. Iterate over the obtained array and sum every item to get the result:

 * Returns the sum of the integers whose index is between i1 and i2.
 * @param array 
 * @param i1 
 * @param i2 
 * @returns {Int} result 
function calc(array, i1, i2){
    let result = 0;

    array.slice(i1, (i2 + 1)).forEach(element => {
        result += element;

    return result;

In the following example are some test cases:

let array = [0, 1, 2, 3, 4, 5, 3];

// 1
console.log(calc(array, 0, 1));

// 15
console.log(calc(array, 0, 5));

// 0
console.log(calc(array, 0, 0));

// 18
console.log(calc(array, 0, 6));

Happy coding ❤️!

This could interest you

Become a more social person