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?

2
  • 2
    You don't. You'll need a variable to refer to the array twice. Chaining doesn't make it "more clear" anyway. Commented Oct 3, 2022 at 3:44
  • this.length is always 1 because this is not what you think it is Commented Oct 3, 2022 at 3:54

1 Answer 1

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/[email protected]/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

2 Comments

That's what I want, clear and easy to read
I did this by extending Array.prototype.sample, I know I shouldn't extend base object, but since this is a greasemonkey script running in sandbox and the only user is myself, I think it's fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.