Helen Araya
Helen Araya

Reputation: 1936

Array.sort and Linq OrderBy give different results

I am trying to do sort an array in C# and in javascript. But I am having a problem that both the sort results are not matching. They both sort differently for example if the input array have underscores.

in C# below is a sample code and Here is a dotnetfiddle link.

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var array= new string[]{"Meter_2","Meter0Add","Meter0Replace","Meter_1","ZZZ"};

        var temp= array.OrderBy(x => x).ToArray();

        foreach(string x in temp)
        {
            Console.WriteLine(x);
        }

    }
}

result: Meter_1, Meter_2, Meter0Add, Meter0Replace, ZZZ

in javascript below is a code sample Here is a js fiddle link.

var array  = ["Meter_2","Meter0Add","Meter0Replace","Meter_1","ZZZ"];
array.sort();
document.writeln(array.join(", "));

result Meter0Add, Meter0Replace, Meter_1, Meter_2, ZZZ

The question is how can I make the javascript the same as the C#?

Upvotes: 2

Views: 2001

Answers (1)

Ori Drori
Ori Drori

Reputation: 191936

JS Array#sort has a default sort order, and is not stable, unless supplied with a compare function. According to MDN:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

If you'll use String#localeCompare as a compare function, you'll get the same results:

var array = ["Meter_2", "Meter0Add", "Meter0Replace", "Meter_1", "ZZZ"];
array.sort(function(a, b) {
  return a.localeCompare(b);
});
console.log(array.join(", "));


Note: You can find more info in this article - Sorting - We're Doing It Wrong

Upvotes: 7

Related Questions