Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I slice an array in KRL

Tags:

arrays

slice

krl

I have a bunch of HTML fragments in an array (thank you query()) but I only want to use the first five. I'm using foreach to inject the fragments into a page.

If my array was [0,1,2,3,4,5,6,7,8] I would want just [0,1,2,3,4]. In Python I would use A[:5].

How can I select the first few elements of an array and ignore the rest?

like image 491
Randall Bohn Avatar asked Mar 21 '26 19:03

Randall Bohn


1 Answers

You can use pick() for this, but it only appears to work correctly if the items in your array are objects, not numbers or strings:

    a = [{'n':"a"},{'n':"b"},{'n':"c"},{'n':"d"}];
    b = a.pick("$[2:]");

in the above example, b == [{'n' :'c'}, {'n' :'d'}]

I've filed a bug about the number and string failures.

It would also be possible to create a recursive function that returned the proper slice of the array, but it does sound a bit painful.

like image 119
TelegramSam Avatar answered Mar 24 '26 14:03

TelegramSam