code_dude
code_dude

Reputation: 1111

I want to add together the numbers of a nested array

This is what I came up with:

var nestedArr = [[[1,2],[3,4]],[[5,6]]];

function sumTotal() {
	for(var i = 0; i < nestedArr.length; i++) {
		for(var j = 0; j < nestedArr[i].length; j++) {
			for(var k = 0; k < nestedArr[i][j].length; k++) {
				var arrNumSum = nestedArr[i][j][k]; 
				arrNumSum += arrNumSum;

				return arrNumSum; 		
			}
		}
	}	
}

sumTotal();

Upvotes: 0

Views: 87

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386550

You could use a recusive call of Array#reduce with a named function as callback.

var array = [[[1, 2], [3, 4]], [[5, 6]]],
    total = array.reduce(function add(r, a) {
        return Array.isArray(a) ? a.reduce(add, r) : r + a;
    }, 0);

console.log(total);

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can instead create recursive function using reduce()

var nestedArr = [[[1,2],[3,4]],[[5,6]]];

function sum(arr) {
  return arr.reduce(function(r, e) {
    return r + (Array.isArray(e) ? sum(e) : e)
  }, 0)
}

console.log(sum(nestedArr))

Upvotes: 7

Thomas
Thomas

Reputation: 181735

You're overwriting arrNumSum each time through the loop. Moreover, you're returning too soon, right after the first iteration. Try this instead:

var nestedArr = [[[1,2],[3,4]],[[5,6]]];

function sumTotal() {
	var arrNumSum = 0;
	for(var i = 0; i < nestedArr.length; i++) {
		for(var j = 0; j < nestedArr[i].length; j++) {
			for(var k = 0; k < nestedArr[i][j].length; k++) {
				arrNumSum += nestedArr[i][j][k];
			}
		}
	} 
	return arrNumSum; 		
}

console.log(sumTotal());

Upvotes: 0

Related Questions