Home > Net >  How to get random single result from multiple rows text from web scraping using Javascript?
How to get random single result from multiple rows text from web scraping using Javascript?

Time:08-05

Is there any way for me to straight away get random single result from the row and output it without having to push to the healthArray?

My main objective is to increase the performance because the row can be up to 200 text and I don't want it to keep pushing to the array.

let randomFact;
let healthArray = []

$(".round-number")
  .find("h3")
  .each(function(i, el) {
    let row = $(el).text().replace(/(\s )/g, " ");
    row = $(el)
      .text()
      .replace(/[0-9] \. /g, "")
      .trim();
    healthArray.push(row);
  });

randomFact = healthArray[
  Math.floor(Math.random() * healthArray.length)
].toString();

CodePudding user response:

You can generate the random number then use eq() to pull the text of the random element straight from the DOM. This would negate the need to build the array.

let $h3 = $('.round-number h3');
let rnd = Math.floor(Math.random() * $h3.length);
let randomFact = $h3.eq(rnd).text().replace(/[0-9] \. /g, '').trim();

Here's a working example:

let $h3 = $('.round-number h3');

$('button').on('click', () => {
  let rnd = Math.floor(Math.random() * $h3.length);
  let randomFact = $h3.eq(rnd).text().replace(/[0-9] \. /g, '').trim();
  console.log(randomFact);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Get random</button>

<div ><h3>Foo</h3></div>
<div ><h3>Bar</h3></div>
<div ><h3>Fizz</h3></div>
<div ><h3>Buzz</h3></div>
<div ><h3>Lorem</h3></div>
<div ><h3>Ipsum</h3></div>

  • Related