Home > Software engineering >  How to get length of previous array in chain function
How to get length of previous array in chain function

Time:10-04

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?

CodePudding user response:

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>

  • Related