Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2011
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Unhappy Need help on a simple basic JavaScript

    Hello guys.

    I need to know how can i write a script to read 20 numbers within 10 - 100 range and print it only if it is not an duplicate of a number that has already been read. I need to do this with only using a single one dimensional array .currently my script is as follows

    Code:
    <script type="text/javascript">
    //creating an array which hold the 20 numbers
    myArray = ["22","32","43","54","65","76","87","98","19","25","11","12","13","14","15","16","17","18","19","22"];
    var flag = 0;
    for (var i = 0; i < myArray.length; i++)
    {
    if (flag != myArray[i])
            {
                    document.write(myArray[i] + " ");
                    flag = myArray[i];
                            
            }
    
    }
    </script>
    The problem with this script is the flag variable dose not hold the all previous values. anyway to do this using a single one dimensional array?

  • #2
    GŁtkodierer
    Join Date
    Apr 2009
    Posts
    2,127
    Thanks
    1
    Thanked 426 Times in 424 Posts
    I won't go into too much detail, since this looks like a homework assignment, but there's at least two ways to do this:

    1.) Sort the array (myArray.sort()) before the loop. This way, it's ok to only compare to the last printed value.

    2.) Put a second loop within the main loop in order to compare the current value to all the previous values.

  • Users who have thanked venegal for this post:

    chaminda (08-20-2011)

  • #3
    New to the CF scene
    Join Date
    Aug 2011
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks venegal, this helps a lot


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •