Slicing is not functionning correctly

Hello Weweb Community,

I think the slicing function on array in not working correctly.

I’m looking to sort reviews per creation time and display the first 6 of them in our collection.

The sort function does work nicely when I use the Desc parameter so that the lasted ones are on the top.

Unfortunately when I bind the slicing function on the array starting from 0 to 5 (6 first elements) the array starts at the index 1 (the second element).

slice(reviews, 0, 5)

Do you know why ?

Does my manipulation is not done correctly ?

Here is a example of the situation : Slice function does not work properly — Tella

Thank in advance,

Hi, the sort is applied at the end, so after the slice, not before. You’re taking the 6 first items then you’re sorting them.

You can use the sort() formula to apply it yourself inside the formula before the slice().

slice(sort(reviews, 'updated_at', 'DESC'), 0, 5)
1 Like

Hi @Alexis ,

It work perfectly. :partying_face:

I reverted the position of order and key within the snipped you shared :

slice(sort(context.page?.['data']?.['reviews'], 'DESC', 'updated_at'), 0, 6)

On last thing to mention is that the slicing of the first 6 items works when I get the slice between 0 and 6.

When it’s set to 0 and 5 it only returns 5 items.

Video : https://tella.video/slicing-index-41gi

Any idea why ?

Thank you !

It doesn’t include the last index, so 0 and 5 mean items from 0 to 4 :slight_smile: (so 5 items in total)

1 Like

A excellent ! I understand. Thank you @Alexis :slight_smile:

@Alexis I am facing the same issue with “filter”, I want to slice 4 elements of an array of objects, I have applied a filter, and feels like the filter is also activated at the end, so my slice function only return 2 objects instead of 4. What function should I use in this case? I tried to play with the filter by key funtion but unsuccessfully.

Filter is always applied at the end (the one from the little button under your formula), so if you want to slice after the filter tou can either

  • Create your own formula and move the filter at the formula level, and then use the slice on the result of your formula where you currently use it
  • Instead of using the filter method, you can use the filter formula, if the basic filter by key is enough

Could you share what you have so we can try to help you build your formula ?

sure @Alexis , I made a loom I think it would be easier:

Create a global formula named “Get Free Classes”, where you bind the collection and apply the filter
Then, use the formula combined with the slice slice(Get Free Classes(), 0,2) :slight_smile:

This way, your filter will be applied before the slice

Amazing seems to be working just fine!

1 Like