0

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 ?

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
user944513
  • 12,247
  • 49
  • 168
  • 318
  • Javascript can't sort array of object because, by default, the set of objects is not ordonned. – hubert Apr 29 '16 at 23:56
  • If you try with only number ( 1 , 2 , 3), it work fine. – hubert Apr 29 '16 at 23:57
  • ok so how we sort this array – user944513 Apr 29 '16 at 23:57
  • You're trying to sort the array by the _results_ of functions called on inner children of objects in the array? You're going to need to write a custom sort function for that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Hamms Apr 29 '16 at 23:58
  • @Hamms, is good. the syntax is `arr.sort([fonctionComparaison])` – hubert Apr 30 '16 at 00:00
  • Possible duplicate of [Sorting an array of JavaScript objects](http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Thriggle Apr 30 '16 at 00:01

3 Answers3

4

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());
});
Community
  • 1
  • 1
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • `s/localCompare/localeCompare` – Hamms Apr 29 '16 at 23:59
  • 1
    @user944513 Why? You can literally drop this in place of your current `arr.sort()` call. – Mike Cluck Apr 30 '16 at 00:03
  • 1
    *"sort only really works "out-of-the-box" when sorting numbers and characters"* - No, it only works "out-of-the-box" on character data. It won't sort numbers numerically, you have to provide a comparitor function for that. – nnnnnn Apr 30 '16 at 00:46
  • 1
    Thanks for the localeCompare suggestion. This helped my coffeescript compiled javascript work correctly when return a - b was misbehaving. – Anthony Roberts Oct 23 '17 at 17:09
1

You have to specify how to sort

arr.sort( (a,b) => a.elem.text().localeCompare(b.elem.text() );
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1
function sortNumber(num1,num2) {return num1 - num2;} var numbs = [5, 17, 29, 48, 4, 21]; 
var sortnumb = numbs.sort(sortNumber);
alert(sortnumb)
WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53
  • Welcome to StackOverflow: if you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar or using Ctrl+K on your keyboard to nicely format and syntax highlight it! – WhatsThePoint Feb 07 '18 at 11:21
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Filnor Feb 07 '18 at 13:41
  • @WhatsThePoint the point (in contrast) is that even though there was no explanation, it was useful to me in solving my problem. Programmers too can understand ugly code, not just machines. However, I agree that explanation helps. – Arundale Ramanathan Nov 11 '18 at 12:57