Preloader
Javascript
  • Estimated reading time: 1 Minute

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

Implementation

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 ❤️!

Share:
Carlos Delgado

Carlos Delgado

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Related articles
JavaScript vs. Python for Data Analysis: Key Differences
30 Jan, 2026
  • Estimated reading time: 5 Minutes
Is Framevuerk Still Relevant in 2026?
3 Jan, 2026
  • Estimated reading time: 5 Minutes
The Best JavaScript i18n Libraries Compared
31 Oct, 2025
  • Estimated reading time: 8 Minutes
How to Build a Simple Photo Editor in the Browser with JavaScript
14 Sep, 2025
  • Estimated reading time: 5 Minutes
Weekly trending
How Modern Crown Technology Makes Dental Visits Easier
6 Jun, 2026
  • Estimated reading time: 10 Minutes
The Technology Behind Smarter Boat Navigation Systems
6 Jun, 2026
  • Estimated reading time: 2 Minutes
The Future of Human Machine Interfaces Is Simpler Than Ever
6 Jun, 2026
  • Estimated reading time: 2 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.