Compute the sum of subarrays within the array in JavaScript

JavaScript is a prominent computer language used for web development, making creating interactive and dynamic webpages possible.

Arrays, flexible data structures that enable storing and manipulating multiple values within a single variable, are at the heart of JavaScript's data manipulation capabilities. JavaScript arrays are very flexible since they can include items of several data kinds, including numbers, strings, objects, or even other arrays. They provide pre-built methods and properties that make adding, deleting, and accessing items more accessible.

Array of elements
Array of elements

JavaScript arrays can also contain subarrays, or arrays that are nested inside of other arrays. Subarrays can aid in arranging and structuring data hierarchically. Developers may rapidly work with data collections, alter subarrays, and carry out numerous actions on items using JavaScript's robust array features, enabling the development of robust and dynamic web applications.

Sub array
Sub array

Possible approaches

Different approaches exist to compute the sum of the subarrays within an array. Two of them are explained below.

Iterative approach

To compute the sum of the subarrays within an array in JavaScript, you can follow these steps.

  1. Initialize a variable, let's call it totalSum, to keep track of the overall sum of the subarrays. Set it to 0 initially.

  2. Iterate over each element in the main array using a loop.

  3. For each element, check if it is an array using the Array.isArray() method. This ensures that we are only considering subarrays.

  4. If the element is indeed an array, iterate over its elements and add them up to a temporary variable, such as subArraySum.

  5. Add the subArraySum to the totalSum to accumulate the sum of all subarrays.

  6. After iterating through all elements in the main array, the totalSum will hold the final sum of all the subarrays.

Implementation

function computeSubarraySum(arr) {
let totalSum = 0;
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let subArraySum = 0;
for (let j = 0; j < arr[i].length; j++) {
subArraySum += arr[i][j];
}
totalSum += subArraySum;
}
}
return totalSum;
}
// Example usage:
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const sum = computeSubarraySum(arr);
console.log(sum); // Output: 45 (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)

In this example, the computeSubarraySum function takes an array as input and follows the steps described above to compute the sum of the subarrays within the array. The example usage demonstrates a two-dimensional array arr consisting of subarrays. The function correctly calculates the sum of the subarrays, resulting in an output of 45.

Complexity

  • The time complexity of the code using a nested loop to compute the sum of subarrays within an array in JavaScript is O(N*M), where N is the number of subarrays in the array, and M is the average number of elements in each subarray.

  • The space complexity of the code is O(1), which requires constant additional space. This is because the only extra space used is for a few variables (totalSum, subArraySum, i, and j) that do not depend on the input size. The space used does not grow with the input array size, making it constant.

Recursive approach

To compute the sum of the subarrays within an array in JavaScript using a recursive approach, you can follow these steps.

  1. Initialize a variable. Let's call it totalSum. This will help to keep track of the overall sum of the subarrays. Set it to 0 initially.

  2. Create a recursive function. Let's call it computeSubarraySumRecursive. This takes the array as an argument.

  3. Within the recursive function, check if the first element of the array is an array itself using Array.isArray(). If it is, recursively call computeSubarraySumRecursive with the subarray as the argument and add the returned value to totalSum.

  4. If the first element of the array is not an array, add it directly to totalSum.

  5. Remove the first element from the array using the slice() method.

  6. Base case: If the array becomes empty after removing the first element, return totalSum.

  7. Recursively call computeSubarraySumRecursive with the updated array and add the returned value to totalSum.

  8. Return totalSum as the final result.

Implementation

function computeSubarraySumRecursive(arr) {
let totalSum = 0;
if (Array.isArray(arr[0])) {
totalSum += computeSubarraySumRecursive(arr[0]);
} else {
totalSum += arr[0];
}
arr = arr.slice(1);
if (arr.length === 0) {
return totalSum;
}
totalSum += computeSubarraySumRecursive(arr);
return totalSum;
}
// Example usage:
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const sum = computeSubarraySumRecursive(arr);
console.log(sum); // Output: 45 (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)

In this example, the computeSubarraySumRecursive function uses a recursive approach to compute the sum of the subarrays within the array. The example usage demonstrates a two-dimensional array arr consisting of subarrays. The function correctly calculates the sum of the subarrays using recursion, resulting in the output of 45.

Complexity

This approach's time and space complexity is O(N), where N represents the total number of elements in the array.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved