1

This is a sample array with 8 objects inside. Now, I want to sort them in ascending order. And I get the result perfectly in console.

const array = 
            [{"lead_location":"a"},{"lead_location":"rta"},
             {"lead_location":"van"},{"lead_location":"svan"},
             {"lead_location":"avan"},{"lead_location":"yvan"}, 
             {"lead_location":"ab"},{"lead_location":"rta"}];

var sort = array.sort((a, b) => (a.lead_location) > (b.lead_location));
console.log(sort); // this array is sorted perfectly

However, If i add more objects in the array (13 in the next example), the array is not sorted well. I am using the same sort method as above. Second array is shown below :

const array = 
            [{"lead_location":"a"},{"lead_location":"rta"},
             {"lead_location":"van"},{"lead_location":"svan"}, 
             {"lead_location":"avan"},{"lead_location":"yvan"}, 
             {"lead_location":"a"},{"lead_location":"rta"},
             {"lead_location":"van"},{"lead_location":"svan"}, 
             {"lead_location":"avan"},{"lead_location":"ab"}, 
             {"lead_location":"rta"}];

    var sort = array.sort((a, b) => (a.lead_location) > (b.lead_location));
    console.log(sort); // this array is not sorted well

I am very confused, how come changing the size of the array will show different result? Anyone can spot my mistake?

fabio.sang
  • 835
  • 8
  • 26
Ho Wei Kang
  • 101
  • 2
  • 10
  • Your comparison function does not meet the requirements for a comparison function. The return value must be a number, either negative zero or positive. – Raymond Chen Jun 03 '18 at 05:06
  • Possible duplicate of [Sort array of objects by string property value in JavaScript](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Raymond Chen Jun 03 '18 at 05:06
  • @RaymondChen, Thanks for your explanation man – Ho Wei Kang Jun 03 '18 at 05:12

1 Answers1

4
let sort = array.sort((a,b) => {
    if(a.lead_location > b.lead_location) return 1;
    if(a.lead_location < b.lead_location) return -1;
    return 0
})

You cannot return true/false for the result. You must specify the order. This should be ascending order. If not swap -1 and 1. 0 means both are equal.

evayly
  • 832
  • 7
  • 18