Skip to main content

Sorting data

Enable sorting

To enable sorting data by columns in ascending/descending order, set the sort parameter of the columns property to true for the required column(s). Multiple sorting is activated by default in case sorting is set for more than one column.

In UI a user can sort data by a single column clicking a column header. For multiple sorting a user holds the Ctrl key and clicks column headers in the order the user wants to apply sorting, in this case the sort index appears in the column header.

The example below shows how to enable sorting for columns:

<script>
import { Grid } from "wx-svelte-grid";
import { getData } from "./common/data";
const { data } = getData();

const columns = [
{ id: "id", width: 50, sort: true },
{ id: "city", header: "City", width: 160, sort: true },
{ id: "email", header: "Email", width: 250, sort: true },
];

</script>

<Grid {data} {columns} />

You can also use the api.exec() method and the sort-rows action to change sorting settings. The example below shows how to sort data by the id column in the descending order at the initialization.

<script>
import { Grid } from "wx-svelte-grid";
import { getData } from "./common/data";
const { data } = getData();

let columns = [
{ id: "id", width: 50, sort: true },
{ id: "city", header: "City", width: 160, sort: true },
{ id: "email", header: "Email", width: 250, sort: true },
{ id: "firstName", header: "First Name", sort: true },
{ id: "lastName", header: "Last Name", sort: true },
];

let api;

const init = (api) => {
api.exec("sort-rows", { key: "id", order: "desc" });
};

</script>

<Grid {data} {columns} bind:api {init} />

Disable multiple sorting

To disable multiple sorting, you should apply the add parameter of the sort-rows action by setting its value to false and use the api.intercept() method. In this case it will be possible to sort data only by one column at a time (a user should click the required column header).

<script>
import { Grid } from "wx-svelte-grid";
import { getData } from "./common/data";
const { data } = getData();

let columns = [
{ id: "id", width: 50, sort: true },
{ id: "city", header: "City", width: 160, sort: true },
{ id: "email", header: "Email", width: 250, sort: true },
{ id: "firstName", header: "First Name", sort: true },
{ id: "lastName", header: "Last Name" },
];

let api;

$: if (api) {
api.intercept("sort-rows", (ev) => {
ev.add = false;
});
}
</script>

<Grid {data} {columns} bind:api />

Related articles: