mercredi 2 mars 2016

Javascript Shuffle Array from Text File

I am looking to pull 5 "random" lines from a text file while not repeating any. Each line from the text file has html code which would be inserted into a side menu. I have read up on the Fisher–Yates shuffle but not sure how to incorporate it in this manner with javascript. Presently I am using the following coding for pulling a single 1 line from the file:

var request = new XMLHttpRequest();
request.onload = function() {
    // get the file contents
    var fileContent = this.responseText;
    // split into lines
    var fileContentLines = fileContent.split( '\n' );
    // get a random index (line number)
    var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
    // extract the value
    var randomLine = fileContentLines[ randomLineIndex ];

    // add the random line in a div
    document.getElementById( 'random-testimonial' ).innerHTML = randomLine;
};
request.open( 'GET', 'content.txt', true );
request.send();

Any assistance is appreciated!




Aucun commentaire:

Enregistrer un commentaire