How to sort numbers ignoring sign

How to sort numbers ignoring sign

mkhsammkhsam Posts: 2Questions: 1Answers: 0

Hi. I have a column with numbers like this: [1, 2, 3, 11, -15, -4] and so on. It could be a positive or negative values. I would like to sort it with ignoring sign. As example I would like to get something like this after sorting my example:
[-15, 11, -4, 3, 2, 1] or [1, 2, 3, -4, 11, -15]? How to do that?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,325Questions: 26Answers: 4,949

    Use Orthogonal data. Use columns.render is shown in the Computed Values docs to return the unsigned number for the sort operation.

    Kevin

  • mkhsammkhsam Posts: 2Questions: 1Answers: 0
    edited November 2021

    Thanks, not clear how to return return the unsigned number for the sort operation and how it can sort in right order my values.
    How it looks for me now:

      <script type="text/javascript">
        $(document).ready(function() {
          $('#my_function').DataTable( {
              ajax: {"url": location.origin + '/api/v1/test_url/',
                     "dataSrc": ""},
              bPaginate: false,
              columns: [
                    {data:"results",
                     render: function ( data, type, row ) {
                            if ( type === 'sort' ) {
                                    return (data >>> 0).toString(2);
                            }
                            return data;
                    }},
                    ]
                  } );
              });
      </script>
    

    What is wrong here?

    Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    toString() wouldn't do it, you need Math.abs() - see here :

            render: function(data, type) {
              if (type === 'sort') {
                return Math.abs(data);
              }
              
              return data;
            }
    

    Colin

Sign In or Register to comment.