tags:

views:

47

answers:

2

I have a small question regarding the sorting of a JavaScript array.

I have an array which holds basically a hashmap: dataOfTheUserArray=new Array(6);, which is basically an array of hashmaps. The map looks like the following:

keys:              values

Symbol              xyz
NumberOfStocks      1o
Price               200

So the array basically contains a map for each symbol.

Now I want to sort the array based on the price of the stock . So what I did was:

dataOfTheUserArray.sort(sortByPriceBought);

//The call back function is
function sortByPriceBought(a, b) {

    var x = a.Price;
    var y = b.Price;
    return ((x >y) ? -1 : ((x < y) ? 1 : 0));
}

After sorting it when I iterate through the array the highest price is in the first and all the rest is not sorted. Is there something I am doing wrong? I would really appreciate if someone can explain if anything went wrong in the code.

+2  A: 

If property, a.Price is a string object, the ordering is made lexically.

Changing the code as follows may solve your problem:

var x = parseInt(a.Price);
var y = parseInt(b.Price);
Zafer
+1  A: 

You can simplify your sorting function using - instead of conditions:

function sortByPriceBought(a, b) {
    return b.Price - a.Price;
}

Make sure, than all elements of array have Price property.

Ivan Nevostruev