Marco
Marco

Reputation: 83

Slate Functions Editor - 1 Table with 2 columns - Sort ASC

I has a table with 2 columns: id_pk and str_name_last_first How can I sort this table by name? if i use lower one.. the id-pk does not fit anymore to name.

var data = {{q_data}}
// data.str_name_last_first.sort();

return data

this example does not works:

employees.sort(function(a, b){
    var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
    if (nameA < nameB) //sort string ascending
        return -1 
    if (nameA > nameB)
        return 1
    return 0 //default return value (no sorting)
})

Upvotes: 1

Views: 435

Answers (3)

Marco
Marco

Reputation: 83

easy if you have the result :-)

var data = {{f_data}}
var data_rows = transformColumnSchemaToRowSchema(data);

data_rows.sort((a, b) => {
    return a.str_team_name - b.str_team_name;
});

data_rows.sort((a, b) => {
    let fa = a.str_name.toLowerCase(),
        fb = b.str_name.toLowerCase();

    if (fa < fb) {
        return -1;
    }
    if (fa > fb) {
        return 1;
    }
    return 0;
});

return transformRowSchemaToColumnSchema(data_rows)

Upvotes: 0

Kabiswa Davis
Kabiswa Davis

Reputation: 21

if the {{q_data}} is a Postgres SQL I recommend adding an ORDER BY in the query

SELECT * from table ORDER BY str_name_last_first ASC

if the {{q_data}} is a phonograph query using the search service then add this to your search request json

 "sort": {
   "str_name_last_first": {
   "order": "asc"
   }
 }

Upvotes: 2

Logan Rhyne
Logan Rhyne

Reputation: 601

I'm assuming q_data is a standard postgres query, in which the results of your query look like this (you can see this in Slate if you click the </> button in the Query results preview panel):

{
  id_pk: ["a", "c", "b"],
  str_name_last_first: ["name1", "name2", "name3"]
}

You almost certainly want to implement sorting as part of the query rather than sorting with a Slate javascript function, which does the "work" of sorting in browser memory. In that case, you simply add an ORDER BY statement to your SQL query.

If, for some reason, you really do need to do some sorting in a Slate javascript function, then with this data structure the easiest approach is to:

  1. Covert the single object with parallel lists of values (column structure) to a single list with key/value pairs for each column (row structure).
  2. Sort the list of objects
  3. Convert the list of objects back to a parallel columns data structure.

The Slate documentation has some example implementation of the conversion between these two commonly used formats for representing tabular data: https://www.palantir.com/docs/foundry/slate/references-convert-rows-columns/

Upvotes: 1

Related Questions