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.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Simpler way (to understand obviously :) ) is
Answer edited to avoid the problem of 'overwriting the function with the result' identified by @pimvdb, and kindly explained by @some (in comments, below).
A simple approach that should cover almost all browsers (I think) is to use a function to sum the array values:
JS Fiddle demo.
Though, for those browsers in which it's available,
reduce()
is far, far simpler.Here:
Live demo: http://jsfiddle.net/bPwYB/
(Note: You would have to polyfill
.reduce()
for IE8.)