I have an array of roughly 10 values, and I was wondering if there was any way with JS or JQuery to add up the highest 6 values and get a total.
Here:
var top6Total = arr
.map(function (v) { return +v; })
.sort(function (a,b) { return a-b; })
.slice( -6 )
.reduce(function (a,b) { return a+b; });
Live demo: http://jsfiddle.net/bPwYB/
(Note: You would have to polyfill .reduce()
for IE8.)
Simpler way (to understand obviously :) ) is
var arr = [1,2,3,4,5,6,7,8,9,10]; // your array
arr = arr.sort(function (a,b) { return a - b; });
var sum=0;
for(var i=0;i<6;i++) {
sum+=arr[i];
}
alert(sum);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With