Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 class="round-number"><h3>Foo</h3></div>
<div class="round-number"><h3>Bar</h3></div>
<div class="round-number"><h3>Fizz</h3></div>
<div class="round-number"><h3>Buzz</h3></div>
<div class="round-number"><h3>Lorem</h3></div>
<div class="round-number"><h3>Ipsum</h3></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading