Table .sort() function not working?

Hi everyone,

I have a Table that I’ve loaded from an external .csv file, and I’d like to sort the table rows by numeric values in a certain column.

However, when I run Table.sort() or Table.sortReverse(), it keeps giving me seemingly randomly sorted data. The table it produces is not sorted by the values in the specified column either ascending or descending, and I cannot find a pattern to the way Processing is sorting the data.

I thought that the issue might be that it’s interpreting the values in that column as a datatype other than integers, so I even tried creating my sorting Table by constructing it one .setInt() at a time (from the .csv file using a for loop). Still the same result, no rhyme or reason to what .sort() or .sortReverse() spit out.

Am I missing something obvious? I haven’t been able to find many resources online about Table.sort() malfunctions. If need be I can post my code, but it’s part of a much larger project…

1 Like

Hi, welcome to the forum.
The best way really is to post a concise small working snippet of your code.
I know it’s a little more work, but that’s the way to get a fast solution.

1 Like

Hello,

This has got me before!

The sort() function is sorting Strings:
https://processing.org/reference/Table_sort_.html It says values but the values are Strings!

See discussion here:
https://forum.processing.org/two/discussion/5028/how-do-i-sort-a-table-based-on-a-numerical-column

Click for Code!
Table table;

void settings() 
  {  
  size(640, 360); 
  }

void setup() 
  {
  table = loadTable("data2.csv"); 
  //table.setColumnType(1, Table.INT); // Try it with and without this!
  table.sort(0);
  //table.sortReverse(0);
     
  for (TableRow row : table.rows()) 
    {
    println(row.getInt(0));
    }  
  }

/*
data2.csv:

10,10
8,8
6,6
5,5
7,7
0,0
4,4
9,9
1,1
3,3
2,2
11,11
100,100
101,101
20,20
200,200
201,201
*/

:)

2 Likes

I actually managed to figure this out – I had to define the table’s columnType as Table.INT, and then Table.sort() worked correctly :slight_smile:

4 Likes