Skip to main content

Sorting data

Enable sorting

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

In UI users can sort data by a single column clicking a column header. For multiple sorting users hold the Ctrl key and click column headers in the order they want 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 sort data programmatically. 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 },
];

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

</script>

<Grid {data} {columns} {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" },
];

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

<Grid {data} {columns} {init} />

Related articles: