Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sum of highest 6 values in an array

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.

like image 888
user1599318 Avatar asked Dec 06 '22 12:12

user1599318


2 Answers

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.)

like image 131
Šime Vidas Avatar answered Dec 11 '22 09:12

Šime Vidas


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);
like image 44
AdityaParab Avatar answered Dec 11 '22 09:12

AdityaParab