How to sum all elements in a nested array?

this is an array which is given:

let arrayNumbers = [ 5, 7, 
        [ 4, [2], 8, [1,3], 2 ], 
        [ 9, [] ], 
        1, 8
      ];

and the output must be 50

This code must be WITHOUT Array.isArray;

let sum = 0;
function treeSum(array) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] === false) {
            treeSum(array[i]);
        } else {
            sum += array[i];
        }
    }
    return sum;
}

treeSum(arrayNumbers);

Help, please with an idea or code, thanks.

You need to use a local sum variable as well to prevent duplicate adding of nested sums.

You could check if the item

  • is an instance of Array with the instanceof operator, of

    function treeSum(array) {
        var sum = 0;
        for (let i = 0; i < array.length; i++) {
            sum += array[i] instanceof Array ? treeSum(array[i]) : array[i];
        }
        return sum;
    }
    
    let arrayNumbers = [5, 7, [4, [2], 8, [1, 3], 2],  [9, []], 1, 8];
    
    console.log(treeSum(arrayNumbers));

    Recursion - Sum Nested Array, As a result of this implementation, all pain and suffering are removed from the program. We do not concern ourselves with local state variables, variable� Sum of product of all pairs of array elements; Count of all possible pairs of array elements with same parity; Minimum sum of product of elements of pairs of the given array; Count of pairs of Array elements which are divisible by K when concatenated; Check if all elements of the given array can be made 0 by decrementing value in pairs

Flatten and reduce the array as below:-

var sum = arrayNumbers.flat(Infinity).reduce((a,b)=>a+b)

Sum of several arrays, More readable example with the possibility to sum the numbers on the nested arrays on many levels. function SumNestedArrays(arr) { return arr.reduce( function (� Before Java 8, the only solution is to iterate the given array using for-each loop and accumulate sum of all elements in a variable. This approach is illustrated here. With introduction of Java 8 Streams API, we can easily get sum of all array elements using Stream.sum () method. To get Stream of array elements, we can use Arrays.stream () method.

You could flat the list then use reduce method to obtain the sum.

You can use if (item.map) condition in order to check if it's array.

let arrayNumbers = [ 5, 7, 
        [ 4, [2], 8, [1,3], 2 ], 
        [ 9, [] ], 
        1, 8
      ];
const flatArray = (arr) => {
    const res = []
    for (const item of arr) {
        if (item.map) {
            const subRes = flatArray(item)
            res.push(...subRes)
        } else {
            res.push(item)
        }
    }
    return res;
}      
console.log(flatArray(arrayNumbers).reduce((a, b) => a + b));

How to sum all elements in a nested array?, isArray; let sum = 0; function treeSum(array) { You need to use a local sum variable as well to prevent duplicate adding of nested sums. You could check if� In case you are looking for the sum of all elements of an arbitrary matrix, here are two shorter routines which do the job: And here is a way to sum up recursively all scalars even in multiple nested matrices (for whatever that may be worth).

You can use recursion. So you need to check whether iterated element is array. If it is array, then run sumArray method again, otherwise you can sum up value:

const sumArray = (arr) => {
  let sum = 0;
  arr.forEach(element => {
    if (typeof element != 'number') {
        sum += sumArray(element);
    } else {
      sum += element
      return sum;
    }
  });
  return sum;
}


console.log(sumArray(arrayNumbers));

An example:

let arrayNumbers = [ 5, 7,
  [ 4, [2], 8, [1,3], 2 ],
  [ 9, [] ],
  1, 8
];

const sumArray = (arr) => {
  let sum = 0;
  arr.forEach(element => {
    if (typeof element != 'number') {
        sum += sumArray(element);
    } else {
      sum += element
      return sum;
    }
  });
  return sum;
}

console.log(sumArray(arrayNumbers));

sum of all element of nested array, sum of all element of nested array with two approaches using functional programming in javascript. S = sum (A,vecdim) sums the elements of A based on the dimensions specified in the vector vecdim. For example, if A is a matrix, then sum (A, [1 2]) is the sum of all elements in A, since every element of a matrix is contained in the array slice defined by dimensions 1 and 2. example.

you can use the combination of 'join', 'split' and reduce

var t =[ 5, 7, 
        [ 4, [2], 8, [1,3], 2 ], 
        [ 9, [] ], 
        1, 8
      ].join().split(',').reduce(function(a,b) { return parseInt(a?a:"0") + parseInt(b?b:"0")})
      
 console.log(t)

sum of all elements in a nested array, using functional programming in javascript we are add all the elements of the nested array with two different approach, and comparing the time taken by both of � The Sum of elements on the boundary is 1 + 2 + 3 + 3 + 3 + 2 + 1 + 1 = 16. The Sum of elements on the diagonals which do not intersect with the boundary elements is 2. Therefore the required sum is 16 + 2 = 18. Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Understand JavaScript Arrays and Common Array Methods with , We talk about what the JavaScript Array is, nested arrays and array The first of the invocations computes the sum of all the values in the array, e.g., 2 + 3 + 5 +� To get the sum of all elements in a numpy array, you can use Numpy’s built-in function sum (). In this tutorial, we shall learn how to use sum () function in our Python programs. Syntax – numpy.sum () The syntax of numpy.sum () is shown below.

Sum of array elements - MATLAB sum, If A is a matrix, then sum(A) returns a row vector containing the sum of each column. If A is a multidimensional array, then sum(A) operates along the first array� Check if Array elements can be maximized upto M by adding all elements from another array; Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum; Count of Array elements greater than all elements on its left and next K elements on its right

Sum of fi array elements - MATLAB sum, If A is a multidimensional array, sum( A ) treats the values along the first non- singleton dimension as vectors, returning an array of row vectors. example. Python program to find N largest elements from a list; Python program to find number of m contiguous elements of a List with a given sum; Python program to swap two elements in a list; Python program to interchange first and last elements in a list; Python program to apply itertools.product to elements of a list of lists

Comments
  • why either "count array elements" or get sum of all? and why 5?
  • arrayNumbers.flat(Infinity).reduce((a, b) => a + b, 0) ?
  • is 50, im trying to fix this
  • Is it worth explaining why you can't use Array.isArray? It's supported all the way down to IE9.
  • If Array.isArray cannot be used, then what else cannot be used either? flat, flatMap, reduce, recursion, typeof, instanceof, constructor, ...? Such requirements make no sense without more context.
  • I cannot do it like this also, that's the problem(
  • Array#reduce throws an error against an empty array if you don't have an initial value. So you should probably set 0 as an initial value of your reducer. Note that Number([]) returns 0 so this would be consistent with how JavaScript would convert an empty array into a number.
  • @PStarter, I used if (item.map) to check if it's array.
  • @customcommander, the OP says This code must be WITHOUT Array.isArray;
  • @customcommander, one possible alternative could be typeof arr.map === 'function'
  • Why .flat().flat() when you can specify a depth? A reducer without an initial value will throw an error if the array is empty. You should specify 0 as an initial value.
  • Thanks for the depth suggestion, and will not give error because it is already have value, otherwise you can use the default value