×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

How to find the sum of a nested array in JavaScript?

By IncludeHelp Last updated : January 21, 2024

In JavaScript, a nested array is an array that has array(s) inside an array i.e., array(s) within the array.

Problem statement

Given a nested array, you have to find all elements of all elements using JavaScript.

Finding the sum of a nested array

To find the sum of a nested array, write a function in which find the sum of all elements that are number type, check if an element is an instance of an array then again call the function itself. This process will add all elements including nested array's elements. And, then return the sum.

JavaScript code to find the sum of a nested array

The following example finds the sum of all elements of a nested arrays arr1 and arr2.

// defining function to return the 
// sum of all elements of a nested array
function sumArrayElements(arr) {
  var sum_elements = 0;
  for (var i = 0; i < arr.length; i++) {
    if (typeof arr[i] == "number") {
      sum_elements += arr[i];
    } else if (arr[i] instanceof Array) {
      sum_elements += sumArrayElements(arr[i]);
    }
  }
  return sum_elements;
}

// creating nested arrays
arr1 = [444, 888, [333, 999], [111]];
arr2 = [10, 20, [1, 2, 3, 4], [5, 6, [7, 8, 9]]];

// getting the sum & printing
console.log("sum of elements of arr1:", sumArrayElements(arr1));
console.log("sum of elements of arr2:", sumArrayElements(arr2));

Output

The output of the above code is:

sum of elements of arr1: 2775
sum of elements of arr2: 75
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.