开发者

JavaScript: Taking the highest 2 numerical values out of a series of 4 possible values

I'm trying to take the highest two values out of 4 possible variables and add them together, while ignoring the lesser two values. My values will be anywhere between 1 and 5.

So, for example, if I have the variables:

Trait 1 = 3
Trait 2 = 3
Trait 3 = 2
Trait 4 = 1

The script should pick up the 3 and the 3, but not the 2 and the 1. If I change the values around so that I have:

Trait 1 = 4
Trait 2 = 3
Trai开发者_如何学Ct 3 = 1
Trait 4 = 5

The script should use the 4 and the 5, but not the 3 and the 1. How would I go about doing this?


Put them in an array and then sort the array descending. After sorting, you'll have the values you need in the first two members.


You may want to consider this approach: (on the same lines as the other answers)

var Trait1 = 4;
var Trait2 = 3;
var Trait3 = 1;
var Trait4 = 5;

var sorted = [Trait1, Trait2, Trait3, Trait4].sort(function (a, b) { 
   return b - a; 
});

console.log(sorted[0] + sorted[1]);    // returns 9

Further reading:

  • Mozilla Dev Center: sort()


Lets assume you are passing the data in as an array of values, aka:

var array = [4, 3, 1, 5];

array.sort(); // becomes [1, 3, 4, 5]

var item1 = newArray[array.length - 1];
var item2 = newArray[array.length - 2];

Just sort and you have the values. Here's a page talking about sorting: http://www.javascriptkit.com/javatutors/arraysort.shtml


What Vanco said in code:

var myarray=[1, 4, 2, 5, 2, 1, 8]
myarray.sort().reverse();
alert(myarray[0] + myarray[1]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜