tags:

views:

68

answers:

4

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
Trait 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?

+2  A: 

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.

Vanco
A: 

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

Tejs
That would give 4 insead of 9 :)
Bastiaan Linders
Updated! I think I was editing when you commented =D
Tejs
This won't work without providing a comparison function because the default sort is lexical. Hence `[4, 3, 10, 5].sort()` will give you `[10, 3, 4, 5]`.
Tim Down
A: 

What Vanco said in code:

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

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:

Daniel Vassallo
This is the best answer, providing working code to back up the technique, and avoids the potential pitfall of not providing a comparison function.
Tim Down