user944513
user944513

Reputation: 12729

why array.sort not work in javascript?

I have array of object .I want if i add object in array it should add in sorted way .I used array to sort .but it not sort my array . here is my code

https://jsfiddle.net/8oczc5x5/

var arr = [{
  elem: {
    text: function() {
      return "aa";
    }
  }
}, {
  elem: {
    text: function() {
      return "yy";
    }
  }
}];
var obj = {
  elem: {
    text: function() {
      return "bb";
    }
  }
}
arr.push(obj);
arr.sort()
console.log(arr[1].elem.text())

Expected Out put

"bb"

Actual output

"yy" 

..why ? I used sort it should sort my array ?

Upvotes: 0

Views: 7917

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You have to specify how to sort

arr.sort( (a,b) => a.elem.text().localeCompare(b.elem.text() );

Upvotes: 2

user7125929
user7125929

Reputation: 85

function sortNumber(num1,num2) {return num1 - num2;} var numbs = [5, 17, 29, 48, 4, 21]; 
var sortnumb = numbs.sort(sortNumber);
alert(sortnumb)

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

sort only really works "out-of-the-box" when sorting character data alphabetically. And why would you expect it to call your functions and compare them? That's really dangerous and complicated. However, you can perform your own special sort by passing it a function.

Taken from the docs (compareFunction is the function you're passing in):

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

If compareFunction(a, b) is greater than 0, sort b to a lower index than a. compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

arr.sort(function(a, b) {
  // localeCompare does a string comparison that returns -1, 0, or 1
  return a.elem.text().localeCompare(b.elem.text());
});

Upvotes: 4

Related Questions