How do I search a extract only a few elements in a huge JS array

Discussion in 'Javascript' started by mdh_2972, Aug 2, 2006.

  1. mdh_2972

    mdh_2972 Guest

    I have an array of over 1000 links in a .JS file. I do not want to put
    the whole thing on my page because it would take to long to render the
    page. So how can I randomly pick 1 element from the array and then have
    the browser just place the 1 element only on my webpage.

    Also I also would like to know how to search for text in the array
    element and place it on my webpage.

    The first example is my main question.
    mdh_2972, Aug 2, 2006
    1. Advertisements

  2. search for a random generator and use the generated number as the array
    for your second question just make a loop:
    for(i=0 i< array.length; i++)
    if("string" == array)
    //found !!

    good luck!
    Jonas Geiregat, Aug 2, 2006
    1. Advertisements

  3. mdh_2972

    RobG Guest

    function returnRandomElement(linkArray){
    return linkArray[Math.random()*linkArray.length|0];

    Where 'linkArray' is something like:

    var linkArray = [

    Using the above array as an example, the following function will return
    the first link that has text matching 'text':

    function returnMatchLink(linkArray, text){
    var i = linkArray.length;
    var re = new RegExp(text);
    while (i--){
    if (re.test(linkArray)){
    return linkArray;
    return 'not found...';


    <button onclick="
    document.getElementById('xx').innerHTML =
    returnMatchLink(linkArray, 'yahoo');
    get 'google'</button>
    <div id="xx"></div>

    Using a substring method rather than a regular expression may be
    RobG, Aug 3, 2006
  4. JRS: In article <44d11c54$0$28398$>, dated Wed,
    2 Aug 2006 23:41:52 remote, seen in Jonas
    Bad advice. Searching may find a bad generator. WHENEVER the newsgroup
    FAQ addresses a topic, MAKE SURE that your response is at least as good
    - and, if it's not significantly better, answer by citing the FAQ.

    FAQ 4.22; 4.15.
    ^ index

    But he wants to search for text in the array element, not necessarily
    for a whole element. For that, the .indexOf and .search methods of
    String, or methods of RegExp, can be used; they are described in the
    usual references. To write the text, FAQ 4.15.

    Read the newsgroup FAQ.
    Dr John Stockton, Aug 3, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.