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 ?

6
  • Javascript can't sort array of object because, by default, the set of objects is not ordonned. Commented Apr 29, 2016 at 23:56
  • If you try with only number ( 1 , 2 , 3), it work fine. Commented Apr 29, 2016 at 23:57
  • ok so how we sort this array Commented Apr 29, 2016 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 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 29, 2016 at 23:58
  • @Hamms, is good. the syntax is arr.sort([fonctionComparaison]) Commented Apr 30, 2016 at 0:00

3 Answers 3

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

4 Comments

s/localCompare/localeCompare
@user944513 Why? You can literally drop this in place of your current arr.sort() call.
"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.
Thanks for the localeCompare suggestion. This helped my coffeescript compiled javascript work correctly when return a - b was misbehaving.
2

You have to specify how to sort

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

Comments

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

3 Comments

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!
While this code snippet may solve the question, including an explanation 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!
@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.

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.