I have a list of strings that I want to use as duration filter options. They are currently sorted alphabetically but I want them to be sorted by length of time. Is this possible?
The strings are:
['1 day', '2 days', '2 weeks', '3 days', '3 hours', '4 days']
What I want is:
['3 hours', '1 day', '2 days', '3 days', '4 days', '2 weeks']
Currently i’m sorting them alphabetically by:
const durations = [...new Set(this.courses.map(item => item.fields.duration).sort((a, b) => a.localeCompare(b)))];
5
Answers
First, create a method to convert the list to the minimum time period which is
hours
,For example
1 day
=24 hours
1 week
=24 * 7 hours
Then
sort
the list by comparing the result ofconvertToHours
method.This is working codesnippet
You can use regular expressions for extracting the
value
andunit
in case there are extra spaces/new lines/(d+)s*(w+)/
.AFAIK you can not parse those "range-strings" into a comparable format with vanilla-js itself, you could however write some code that does so, or use a library that can do this somehow, in example dayjs
Personally i would just blow up the inital array with comparable data, something like:
And then you would sort for
hours
and only displaylabel
To sort the durations by length of time, you can convert each duration to a common unit (like hours) and sort based on that. Here’s how you can do it:
This code first maps each duration to an object that contains the original duration string and its equivalent value in hours. Then it sorts these objects based on the value in hours, and finally maps the sorted objects back to an array of duration strings.
There are several ways to achieve that result.. one is converting those durations to scalar using a common unit (hours in this case) so that they will be comparable for the sake of sorting.
In this demo I have a function that convert the duration given as string to scalar as the equivalent amount of hours that will be used in the sort callback function to decide which one comes first in the sort order.
I see other answers came before this one.. I guess this one doesn’t add that much.
For every type of time hour, day and week I assign the equivalent number of minutes and I use it to create a map to assign a value to every time in array, in order to sort it on value calculated.