Skip to content

Instantly share code, notes, and snippets.

@bignimbus
Last active August 29, 2015 13:57
Show Gist options
  • Save bignimbus/9527863 to your computer and use it in GitHub Desktop.
Save bignimbus/9527863 to your computer and use it in GitHub Desktop.
Given a JavaScript array, function flattens the array and returns the sum of all primitive-type numbers in the array. The function works recursively.
/*
Given a JavaScript array, function flattens the array and returns the sum of all primitive-type numbers in the array.
The function works recursively.
*/
function flattenAndAdd(arrayToFlatten) {
var originalArray = arrayToFlatten;
var repeat = 1;
var flatArray = (function checkObject() {
while (repeat > 0) {
repeat = 0;
for (var n in originalArray) {
if (typeof originalArray[n] === "object") {
for (var nN in originalArray[n]) {
originalArray.push(originalArray[n][nN]);
repeat += 1;
}
}
}
}
return originalArray;
})();
var finalSum = (function () {
var sum = 0,
m;
for (m in flatArray) {
if (typeof flatArray[m] === "number") {
sum += flatArray[m];
}
}
return sum;
})();
console.log(finalSum);
return finalSum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment