will there be any change if numeric:true is set in localeCompare function

I have table values with numeric and string types and want to know that setting numeric true will bring any changes for sorting string values in the column

1 answer

  • answered 2019-10-15 14:49 VLAZ

    Yes, treating data as numeric can indeed change the order. Consider this:

    const column = [ "1", "3", "10", "24", "212" ];
    
    column.sort((a, b) => a.localeCompare(b));
    console.log("lexicographical sort:", column);
    
    column.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
    console.log("sort with numeric collation:", column);

    Lexicographical sorting treatsl "10" a before "2" because "1" < "2" as opposed to checking the entire numbers. This can work if you have the same names, too:

    const column = [ "file_1", "file_3", "file_10", "file_24", "file_212" ];
    
    column.sort((a, b) => a.localeCompare(b));
    console.log("lexicographical sort:", column);
    
    column.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
    console.log("sort with numeric collation:", column);

    But might be undesirable in some situations, if you don't want to treat numbers as a whole unit:

    const column = [ "1 Somewhere Street", "3 Some Avenue", "10 Some Avenue", "24 Parking", "212 Whatever Road" ];
    
    column.sort((a, b) => a.localeCompare(b));
    console.log("lexicographical sort:", column);
    
    column.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
    console.log("sort with numeric collation:", column);
    
    column.sort((a, b) => {
      const regex = /^(\d+)\s+(.*)/;
      const [, numericA, stringA] = a.match(regex);
      const [, numericB, stringB] = b.match(regex);
      
      return stringA.localeCompare(stringB) 
        || numericA.localeCompare(numericB, undefined, { numeric: true })
    });
    console.log("sort with starting numerics treated last:", column);

    So, it depends on what your data looks like and how you want it presented.