Last active
August 29, 2015 13:57
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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