Sort items within repeater

I’m calculating distances from point A (obtained by using currentGeolocation function) to variable destinations (listed on a data collection) using Google Maps Distance Matrix inside a repeater onItemReady function. At this point, everything is working well:

    $w("#repeater1").onItemReady(($item, itemData, index) => {

        $item('#placeId').text = itemData.placeId;

        distanceMatrix(geolocationId, itemData.placeId)
        .then(function(json) {

            let duration = json.rows[0].elements[0].duration["text"];
            let kilometersText = json.rows[0].elements[0].distance["text"]
                        
            $item('#km').text = kilometersText;
            $item('#duration').text = duration;
            
        });

    });

This is the outcome that I’m receiving:

As you can see, I’m successfully obtaining the distance between point A to every variable destination in kilometers, as well as the duration in minutes. My concern is the next:

How can I sort these results by duration? From fastest to slowest?

These are the things I’ve tried without success:

– Sort data within repeater (since the distance and the duration do not exist in the database collection, thus I can’t sort them by a query).
– Save repeater’s data (including distance and duration) to a database collection, so then I can query that database sorting by duration.

I tried to be the most clear and practical as possible with my explanation, thanks in advance!

You are mixing data presentation with data computation/retrieval .

You should split those 2 actions into 2 functions

repeater.onReady is meant to bind data to a repeater container. Its only role is to present the data associated with an item. You should not compute/fetch data within that function.

You should retrieve the data outside of the repeater (with wix-data or via your dataset). Compute your distances then insert that data inside your repeater

something like

$w("#repeater1").onItemReady(($item, itemData, index)=>{

   $item('#placeId').text = itemData.placeId;
   $item('#km').text = itemData.kilometersText;
   $item('#duration').text = itemData.duration;
})

const data = getData() //use wix Data or dataset to retrieve data
const dataWithDistance = setDistanceForItems(data) // add the distance information (kilometersText, duration)

$repeater.data = dataWithDistance

As Kentin said you should first add the distance to the data.
Then you can sort it using JS sort method before you assign it to the repeater.

data = data.sort((a,b) => a.distance - b.distance);//for ascending sort. assuming that distance is of type number 

In order to store the data in your collection, use the wixData.bulkUpdate method.

Hi! Thank you very much for your responses, I’m going to play out with these suggestions & evaluate the results. :wink: