getOptions
Description
The function returns the list of options for a specified fieldThe getOptions
helper extracts unique values from a data array based on a specific field.
Usage
getOptions:(
data: any[],
field: string,
config?: {
predicate?: "month" | "year",
sort?: boolean | (a:any, b:any) => number
}
): any[];
Parameters
data
– (required) a data array to extract values fromfield
– (required) ID of the field to extract options fromconfig
- (optional) an object with:predicate
– (optional) extracts month or year from date fieldssort
– (optional) a comparison function to sort the result. Dates and numbers are sorted by default in the ascending order; to cancel this, set thesort
parameter to false.
Returns
An array of unique options for the required field.
Example
Take the following dataset:
[
{ first_name: "Alex", age: 26,start: new Date(2025, 0, 3) },
{ first_name: "Alex", age: 45, start: new Date(2025, 2, 13) },
{ first_name: "Agata", age: 35, start: new Date(2024, 2, 8) },
]
In the example below the getOptions
extracts unique names from the "first_name" field and sorts them in a descending order:
<script>
import { getData } from "../data";
import { FilterEditor, getOptions } from "wx-svelte-filter";
const { data } = getData();
const options = getOptions(data, "first_name", {
sort:((a, b) => a - b)
});
</script>
<FilterEditor field="first_name" type="text" {options}/>
In the next example the getOptions
extracts unique year numbers from the "start" field (sorted by default). Such can should be used in "number" or "tuple" filters:
<script>
import { getData } from "../data";
import { Filter, getOptions } from "wx-svelte-filter";
const { data } = getData();
// Get year numbers from "start" date field
// [ 2024, 2025 ]
const options = getOptions(data, "start", {
predicate: "year",
});
</script>
<Filter field="start" type="number" {options}/>