0

I know that there is a similar question, Javascript - sort objects in an array alphabetically on one property of the array, but when I run step by step using this method it jumps over the sort.

I have an array of objects which looks like this in console:

0:{id: "3645256536754", name: "john", description: "man", children: Array(0)}
1:{id: "8672092533958", name: "alex", description: "man", children: Array(2)}

I must do a forEach on it but before I must be sure that it is in alphabetical order based on the name property.

I did it like this:

myArray.sort(function (a, b) {
    var textA = a.name.toUpperCase();
    var textB = b.name.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
})

When I run it step by step it jumps over this piece of code, I don't know why. Any suggestions?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125

1 Answers1

9

Using the comment by @gurvinder372 as influence, you should do the following:

myArray.sort(function (a, b) {
  var textA = a.name.toUpperCase();
  var textB = b.name.toUpperCase();

  return textA.localeCompare(textB);
});
George
  • 1,706
  • 1
  • 11
  • 12