Web Analytics Made Easy -
StatCounter Need help on a simple basic JavaScript - CodingForum

Announcement

Collapse
No announcement yet.

Need help on a simple basic JavaScript

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    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.
    .My new Javascript tutorial site: http://reallifejs.com/
    .Latest article: Calculators — Tiny jQuery calculator, Full-fledged OOP calculator, Big number calculator
    .Latest quick-bit: Including jQuery — Environment-aware minification and CDNs with local fallback

    Comment


    • #3
      Thanks venegal, this helps a lot

      Comment

      Working...
      X