Javascript sum of the highest values ​​in the array

I have an array of about 10 values, and I was wondering if there is any way with JS or JQuery to add the highest values ​​of 6 and get the total.

+4
source share
4 answers

Here:

var top6Total = arr .map(function (v) { return +v; }) .sort(function (a,b) { return ab; }) .slice( -6 ) .reduce(function (a,b) { return a+b; }); 

Live demo: http://jsfiddle.net/bPwYB/

(Note: you need polyfill .reduce() for IE8.)

+8
source

Simplified way (understand, obviously :))

 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); 
+5
source
 var sortedArr = arr.sort(function (a,b) { return b - a; }); var sum = 0; for (var i = 0; i < 6; i++) sum += sortedArr[i]; 
+1
source

The answer has been edited to avoid the problem of "overwriting the function with the result" identified by @pimvdb and kindly explained by @some (in the comments below).

A simple approach that should cover almost all browsers (I think) is to use a function to sum the values ​​of the array:

 var vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function arraySum(arr) { if (!arr) { return false; } else { var sum = 0; for (var i = 0, len = arr.length; i < len; i++) { sum += arr[i]; } return sum; } } sum = arraySum(vals.sort(function(a, b) { return b - a; }).slice(0, 6)); console.log(sum);​ 

JS Fiddle demo .

Although for those browsers in which it is available, reduce() much simpler.

+1
source

All Articles