1

Try to do something with array with unpredictable result, something like return random member of filtered array

let tempArr = [1,2,3,4,5].filter(x=>x>2);
return tempArr[Math.floor(Math.random()*tempArr.length)];  // 3, 4 or 5

Just want to make it more clear by using chain function, but the following code is not working, this.length is always 1

return [1,2,3,4,5]
         .filter(x=>x>2)
         .at(Math.floor(Math.random()*this.length)); // always returns `3`

What's the correct way to do this?

Byzod
  • 466
  • 4
  • 18

1 Answers1

2

I doubt you can achieve that flow with vanila js, but if you use something like the lodash library, you can make the chain and make code more readable.

const result = _([1,2,3,4,5])
  .filter(x => x > 2)
  .sample();
  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48
  • That's what I want, clear and easy to read – Byzod Oct 04 '22 at 05:26
  • I did this by extending `Array.prototype.sample`, I know [I shouldn't extend base object](https://stackoverflow.com/questions/21945675/extending-array-prototype-in-javascript/21945724#21945724), but since this is a greasemonkey script running in sandbox and the only user is myself, I think it's fine :) – Byzod Oct 04 '22 at 05:49