Skip to content

Instantly share code, notes, and snippets.

@dmitrykuznetsovdev
Last active December 1, 2016 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitrykuznetsovdev/0ccbe86d1223179edd0797443ccb9ddd to your computer and use it in GitHub Desktop.
Save dmitrykuznetsovdev/0ccbe86d1223179edd0797443ccb9ddd to your computer and use it in GitHub Desktop.
Calculate the Max/Min/Avg value from an array
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