Sum of integers in an array (Non-recursive)
From You Can't JavaScript Under Pressure (Q5)
by tonytlwu
HTML
<div id="debug"></div>
JavaScript
// i will be an array, containing integers, strings and/or arrays like itself.
// Sum all the integers you find, anywhere in the nest of arrays.
function addNumber(arr) {
var sum = 0;
/*
* PSEUDO CODE (1)
* ===============
* - Initiate an empty array (flatArray) - this will be used to store a flattened version of the input array
* - Loop through the input array and examine the first element by shifting it out of the input array
* -- If the first element is not an array, push it to the flatArray array
* -- If the first element is an array, loop through it and push all the child elements of the first element into a temporary array. Also raise a flag to mark that the loop encountered an array
* - Once the loop is over, the input arry should be empty.
* - Replace the input array variable with the temporary array
* - Keep running the loop until no array is countered
*/
var flatArray = [];
var tempArray = [];
do {
tempArray = []; // If this is not reset to an empty array, arr will become really long...
while (arr.length) {
var firstElement = arr.shift(); // Using shift instead of arr[0] makes sure that arr[0] is removed from the original array. Otherwise the loop will go on forever.
if (!Array.isArray(firstElement)) {
flatArray.push(firstElement);
} else {
tempArray = tempArray.concat(firstElement);
}
}
arr = tempArray;
} while (arr.length);
arr = flatArray;
for (var n = 0; n < arr.length; n++) {
if (typeof arr[n] === "number") {
sum += arr[n];
} else if (Array.isArray(arr[n]) === true) {
arr = arr[n];
}
}
return sum;
}
var testArray = [1, 2, [1, "a", 2, [1, 2, 3]], 4];
window.debug.innerHTML = addNumber(testArray);