Last active
December 1, 2016 10:41
-
-
Save dmitrykuznetsovdev/0ccbe86d1223179edd0797443ccb9ddd to your computer and use it in GitHub Desktop.
Calculate the Max/Min/Avg value from an array
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
let collection = [1, 2, 3, 4, 5, 6, null, undefined, 7, 8, 9, 10]; | |
collection = collection.filter(a => !!a); | |
let max = (prev, current)=> { | |
return prev > current ? prev : current; | |
} | |
let min = (prev, current)=> { | |
return prev < current ? prev : current; | |
} | |
let sum = (prev, current)=> { | |
return prev + current; | |
} | |
let avg = (prev, current, index, arr)=> { | |
return prev + (current / arr.length); | |
} | |
let rMax = collection.reduce(max); | |
let rMix = collection.reduce(min); | |
let rSum = collection.reduce(sum); | |
let rAvg = collection.reduce(avg, 0); | |
let rAvg2 = collection | |
.map((current, i, arr) => current / arr.length) | |
.reduce((prev, current)=> { | |
return prev + current; | |
}); | |
Math.max(...collection); | |
Math.min(...collection); | |
Math.max.apply(null, collection); | |
Math.min.apply(null, collection); | |
console.log(rMax, rMix, rSum, rAvg, rAvg2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment