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 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.