2

I am sorting an array of objects on one of their properties alphabetically. Currently my sort function is:

var sortFunc = function(a, b) {
    if (a.name < b.name) return -1;
    if (a.name > b.name) return 1;
    return 0;
};
    arr.sort(sortFunc);

However, I am using the index of these objects in the array to display them, and it turns out this sort function is rearranging the objects in a rather unexpected way. It properly sorts alphabetically every time, however when there are multiple objects with the same name property (the string that is compared in the sort function) the items are rearranged every single sort. Their name stays the same, but running the sort function multiple times continually reorders objects that have the same name property value.

Example:

Object A has name "Joe" (index 0)
Object B has name "Bob" (index 1)
Object C has name "Zander" (index 2)
Object D has name "Joe" (index 3)

Running the sort function the first time will yield an order something like this: BADC

Running it again though, on the newly now sorted array, will yield either BADC or BDAC.

How can I prevent shuffling of objects when the property that they are sorted on is the same?

Lucas Penney
  • 2,624
  • 4
  • 27
  • 36

0 Answers0