3.- Sort column when you click on it.
p167Fi_javascript_json_csv_ordena.aia (22.6 KB)
- Now when you click on a column it is ordered directly or inversely.
- Restriction: numbers without decimal separator.
ordena.htm
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head><body>
<p id="demo"></p>
<script>
var data = window.AppInventor.getWebViewString(); // Entrada de datos.
parte = data.split("|");
ordena = parte[0]; // sort this column
reverse = parte[1]; // reverse (1 or -1)
datos = parte[2]; // datos
datos = JSON.stringify(datos);
datos = eval(datos);
datos = JSON.parse(datos);
//////////////////////////////////// Ordena columnas de numeros. Numbers.
const sort_by2 = (field, reverse, primer) => {
const key = primer ?
function(x) {
return primer(x[field])
} :
function(x) {
return x[field]
};
// reverse = !reverse ? 1 : -1;
return function(a, b) {
return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
}
}
///////////////////////////////// Ordena columnas de cadenas. Strings.
var sort_by = function() {
var fields = [].slice.call(arguments),
n_fields = fields.length;
return function(A, B) {
var a, b, field, key, primer, result;
for (var i = 0, l = n_fields; i < l; i++) {
result = 0;
field = fields[i];
key = typeof field === 'string' ? field : field.name;
a = A[key];
b = B[key];
if (typeof field.primer !== 'undefined') {
a = field.primer(a);
b = field.primer(b);
}
// reverse = (field.reverse) ? -1 : 1;
if (a < b) result = reverse * -1;
if (a > b) result = reverse * 1;
if (result !== 0) break;
}
return result;
}
}
JsonFields = ["id","Country","Populat.","Capital","Área"]; // Cabecera. Header.
Columnas_ordenar = ["id","Country","Population","Capital","Area"]; // Ordenar una.
var ordena_esta = Columnas_ordenar[ordena];
if (ordena == 2 || ordena == 4) { // Columnas numéricas 2 and 4. Columns with numbers.
datos.sort(sort_by2(ordena_esta, reverse, parseInt)); // Numeros
} else {
datos.sort(sort_by(ordena_esta, {name: ordena_esta,primer: parseInt,reverse: reverse})); // Cadenas
}
////////////// Presentacion en csv //////////////////////////////////
function JsonToCSV(){
var csvStr = JsonFields.join(",") + "\n";
datos.forEach(element => {
f1 = element.id;
f2 = element.Country;
f3 = element.Population;
f4 = element.Capital;
f5 = element.Area;
csvStr += f1 + ',' + f2 + ',' + f3 + ',' + f4 + ',' + f5 + "\n"; })
return csvStr;
}
window.AppInventor.setWebViewString("" +JsonToCSV()); // Respuesta a CadenaDeWebView
// document.getElementById("demo").innerHTML = JsonToCSV(); // Web
</script>
</body></html>
Base code with modifications: