www.webdeveloper.com
Results 1 to 5 of 5

Thread: Trying to avoid duplicate values in an array

  1. #1
    Join Date
    Jan 2018
    Posts
    1

    Trying to avoid duplicate values in an array

    Greetings,

    The task consists in displaying 2 lists of random numbers
    The first list should have 5 numbers in the range of 1 to 50
    The second list - 2 numbers in the range 1 to 12

    I created the following script which does the job except that occasionally it creates duplicate values which I cannot have.

    =============================================================

    <!DOCTYPE html>
    <html>
    <div id="main" style="margin-left: 300px;">
    <p> Please click below to get your random numbers </p>
    <input type="button" value=" RESET " onClick="document.location.reload(true)"><br><br>
    <p style="color: blue font-style:bold;"> The following numbers are in 0 to 50 range</p><br>

    <script>


    for (i = 0; i < 5; i++){
    var nr=Math.floor(Math.random()*50);

    if (nr!=0){
    document.write("Your lucky number is " + nr +"<br>");
    }else{
    document.write("Your lucky number is " + Math.floor(Math.random()*50) +"<br>");
    }


    }
    document.write("<br><br>");
    document.write("The following numbers are in 0 to 12 range " +"<br><br><br>");

    for (i = 0; i < 2; i++){
    var nr=Math.floor(Math.random()*12);
    if (nr!=0){
    document.write("Your lucky number is " + nr +"<br>");
    }else{
    document.write("Your lucky number is " + Math.floor(Math.random()*12) +"<br>");
    }


    }

    /*
    var con=[2,3,4,5,9];
    for (i = 0; i < 5; i++){

    document.write(can[i]);
    //var div = document.getElementById("textDiv").innerHTML=con[2];
    }


    for (i = 0; i < 5; i++){
    var con=[2,3,4,5,9];
    var div = document.getElementById("textDiv");
    div.textContent = con[i] ;
    var text = div.textContent;
    } */



    </script>
    </div>
    </html>

    ====================================

    So I started creating a second script which would check for duplicates before placing the values within an array and before printing it out and that's were things started getting ugly.
    Please see below:
    ===================================

    <script>


    window.onload=function() {

    first();
    // body...
    }

    var arr1=[];
    arr1.length=5;


    function first() {

    for (i = 0; i < 5; i++){


    var nr = Math.floor(Math.random()*50);

    if(isDup(nr)!=true){
    arr1.push(nr);
    document.write(arr1[i]);
    }

    else{


    arr1.push(Math.floor(Math.random()*50));
    document.write(arr1[i]);

    }


    }

    }



    function isDup(val){
    for(j=0; j<arr1.length; j++){
    if(arr1[j]===val){
    return true;



    }
    else{
    continue;

    }
    }

    }


    document.write("<br><br>");
    document.write("The following numbers are in 0 to 12 range " +"<br><br><br>");

    for (i = 0; i < 2; i++){
    var nr=Math.floor(Math.random()*12);
    if (nr!=0){
    document.write("Your lucky number is " + nr +"<br>");
    }else{
    document.write("Your lucky number is " + Math.floor(Math.random()*12) +"<br>");
    }


    }

    </script>

    ===============================================================

    So here I stand in front of all of you , wise and most honorable Developers, and ask you to take a gander and maybe shed some light over this miserable creation of mine.

    Much Obliged,

    Boris

  2. #2
    Join Date
    Dec 2012
    Posts
    1,626
    This question is asked frequently. I recommend the following procedure:
    Create two arrays containing the numbers of the required ranges.
    Shuffle these arrays, code e. g. here:
    https://stackoverflow.com/questions/...uffle-an-array
    Read the first five numbers from the corresponding array and enter them to the first result array.
    Read the first numbers from the other array. Check if the current number is in the first result array (function indexOf) and if not enter the number to the second result array.
    Repeat this until two numbers have been found.
    Last edited by Sempervivum; 01-26-2018 at 04:37 PM.

  3. #3
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,859
    When posting code, please use the appropriate forum BB code tag to wrap around that block of code, examples in my signature.

    I guess that the project is some kind of assignment judging by its code base.

    So, to avoid duplicate, well the old skool and classical way of teaching this requires two arrays, the original array of data and an array that you then put the item checked in to an array...
    Code:
    function removeDuplicates( ary ){
    if( !arguments.length ) return [];
    var out = [];
    while( ary.length ){
    	chk = ary.shift();
    	if( ary.indexOf( chk ) >-1 ){
    		// we do not bother putting this item in the array as it is a duplicate
    	}else{
    		out.push( chk ); // not a duplicate
    	}
    }
    return out;	
    }
    array = removeDuplicates(["Banana","Cat","Zebra","Matches","Water","Paper","Dog","Lemon","Cat","Bird","Water","Elephant"]);
    console.log("Out = %s ",array.toString()); // outputs : Out = Banana,Zebra,Matches,Paper,Dog,Lemon,Cat,Bird,Water,Elephant 
    array = removeDuplicates([1,4,8,7,8,5,6,4,5,3,4,3,3,2,7,8,9,1]);
    console.log("Out = %s ",array.toString()); // outputs : Out = 6,5,4,3,2,7,8,9,1
    The code can be simplified and take advantage of the array filtering and mapping tools that are now available and do this in a single instruction line.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    5,859
    To illustrate that point, you can swap
    Code:
    function removeDuplicates( ary ){
    if( !arguments.length ) return [];
    var out = [];
    while( ary.length ){
    	chk = ary.shift();
    	if( ary.indexOf( chk ) >-1 ){
    		// we do not bother putting this item in the array as it is a duplicate
    	}else{
    		out.push( chk ); // not a duplicate
    	}
    }
    return out;	
    }
    for
    Code:
    function removeDuplicates(arr) {
        return result = arr.filter((value, index, array) => array.indexOf(value) == index);
    }
    that does the same sort of thing in removing duplicates.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

  5. #5
    Join Date
    Jan 2018
    Location
    3473 Stout Street, Denver, PA 17517
    Posts
    11
    You can use the JavaScript Filter method to check duplicates in an array.

    Example:

    Code:
    function removeDuplicateUsingFilter(arr){
        let unique_array = arr.filter(function(elem, index, self) {
            return index == self.indexOf(elem);
        });
        return unique_array
    }
    
    console.log(removeDuplicateUsingFilter(array_with_duplicates));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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

"

"

X vBulletin 4.2.2 Debug Information

  • Page Generation 0.15931 seconds
  • Memory Usage 2,889KB
  • Queries Executed 13 (?)
More Information
Template Usage (33):
  • (1)SHOWTHREAD
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (4)bbcode_code
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (5)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (5)postbit
  • (5)postbit_onlinestatus
  • (5)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (70):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates