1

I have an array, for example, it has 100 length, and I need to select a specific number of values from an array, for example, I want any 5 values from an array. How to do this?

I saw Karate : Select 'n' number of random values from an Array but here I don't provide a specific number of values. So this is not my case(

Holgar
  • 91
  • 5

1 Answers1

0

This becomes a JS problem. I'll just provide one option that may be sufficient. Here we get 2 random elements.

* def data = ['a', 'b', 'c', 'd', 'e']
* def filtered = data.filter(x => Math.random() < 0.5)
* def selected = filtered.slice(0, 2)

You are welcome to write a more robust function, refer this answer: How to get a number of random elements from an array?

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 1
    I took the next: * def filtered = slugList.sort(() => 0.5 - Math.random()) * def selected = filtered .slice(0, 2) And it works ok for me because the previous shows me the same result (has only 2-3 combinations), for some reason( – Holgar May 08 '23 at 09:43