Explanation to the posted problem
function addArrayElems(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number") sum += arr[i];
for (var j = 0; j < arr.length; j++) {
if (typeof arr[i][j] === "number") sum += arr[i][j];
//added this line here. If arr[i][j] is defined and [i][j][0] return sum.
if (arr[i][j] && typeof arr[i][j][0] === "number") sum += arr[i][j][0];
}
for (var l = 0; l < arr.length; l++) {
if (typeof arr[i][j] === "number") sum += arr[i][j];
}
}
return sum;
}
var arr = [1, 2, 3, 4, 5, [6, 7, 8, [9], [10]]];
console.log(addArrayElems(arr));
In your own code you iterated over the parent array arr
. When you access arr[i]
this will always work. JavaScript will return a value if set or else returns undefined
. However when you try to access a property on an non-property (undefined
) this will return a script error. You can't ask for the colour of an object that doesn't exist. The code above should return the desired results based upon the sample you've provided (Since the third level arrays are only 1 in length). The above example is just to explain how accessing values in multidimensional arrays work. However you want to do this recursively. I shall show you an example here below:
Improved answer (http://jsfiddle.net/o80e7f53/)
function addArrayElems(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number")
{
sum += parseInt(arr[i]); //parse number and add to sum.
}
else if (Object.prototype.toString.call(arr[i]) === '[object Array]')
{
sum += addArrayElems(arr[i]);
}
}
return sum;
}
var arr = [1, 2, 3, 4, 5, [6, 7, 8, [9], [10]]];
console.log(addArrayElems(arr));
A recursive function calls itself again. Essentially if your multidimensional array is 100 arrays deep this function would still return all values. In your approach this should take 100 for loops you needed to write singlehandedly. This function loops over the values of an array and returns the sum when a number is found. If an array object is found the function call itself again except with the current array object. The returned result gets stored into sum. When the function finally returns to the first function call; sum
contains all values from each array level.