- Apply a limit of items for a group of sources
- Remove duplicates in a group of sources
- Group sources by an attribute
- Sort sources
Create a reshape function
To remove duplicates between sources, you can start by creating auniqBy function.
You can later apply this function to your recent searches
and Query Suggestions sources.
JavaScript
filter(Boolean).
The reshape function
Now that you’ve created theuniqBy function,
you can specify the implementation for your sources and use it in the
reshape option:
JavaScript
sources: the resolved sources provided bygetSourcessourcesBySourceId: the resolved sources grouped bysourceIdstate: the Autocomplete state
uniqBy function uses item.query as identifier for the Query Suggestions plugin
and item.label for the recent searches plugin.
These are the shape of the items that the plugins return.
If you use custom sources, you can use a switch statement based on source.sourceId.
Sources are retrieved from sourcesBySourceId with their sourceId using object destructuring.
You can return sources that you didn’t reshape with Object.values(rest).
Combine reshape functions
You can create a function that combines results from two different sources. Use it withuniqBy to ensure there are no duplicates and there’s a fixed number of combined items.
In the video, four results are always displayed and the number of Query Suggestions varies depending on the number of recent searches.
Here’s a limit function:
JavaScript
uniqBy and limit functions:
JavaScript
Pipe reshape functions
Nested function calls can become cumbersome, so you can use functional libraries like Ramda to pipe reshape functions instead.JavaScript
For your reshape functions to support
pipe,
you need to make sure your sources are one level deep,
for example using Array.flat.