Last active
July 21, 2018 17:12
-
-
Save adyngom/d37d062b0bf8db41b6d86491daa6db04 to your computer and use it in GitHub Desktop.
Given a deeply nested array in Javascript find the sum of all the numeric values
This file contains 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
// Caculate sum of numbers in nested array | |
//----------------------------------------// | |
const arrSet = [[1,2,3],4,5,"h","e",["l","o", null, false, true], 3.75, -1]; | |
const FlattenArray = function(arr) { | |
return arr.reduce((a,c) => { | |
return Array.isArray(c) ? a.concat(FlattenArray(c)) : a.concat(c); | |
}, []); | |
} | |
const FlattenArrayByString = function(arr) { | |
return arr.toString().split(','); | |
} | |
const MakeArray = function() { | |
return (Array.isArray(arguments[0])) ? arguments[0] : [...arguments]; | |
} | |
const NumbersOnly = function(args) { | |
let numberSet = []; | |
args.forEach(a => { | |
let x = parseFloat(a); | |
if(!isNaN(x)) numberSet.push(x); | |
}) | |
return numberSet; | |
} | |
const ArraySum = function(arr) { | |
return arr.reduce((p,n) => { return p + n; }, 0) | |
} | |
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); | |
const getArraySum = compose(ArraySum, NumbersOnly, FlattenArray, MakeArray); | |
const getArraySum2 = compose(ArraySum, NumbersOnly, FlattenArrayByString, MakeArray); | |
console.log(getArraySum(arrSet)); | |
console.log(getArraySum2(arrSet)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment