find duplicates in array

Given an array of unknown size and containing only integers between 0 to 30 (inclusive), write an algorithm to find which numbers are duplicated, if any.

var arr = [ 8, 5, 3, 7, 5, 0, 2, 2, 7, 7, 4, 5, 7, 3, 1 ]; // input array
 
function find_duplicates_array( input_arr ) {
    var i,
        ind,
        arr_len,
        duplicates_arr = [],
        counts_arr = [];
 
    arr_len = input_arr.length;
 
    for ( i = 0; i < arr_len; i++ ) { // run thru array
        ind = input_arr[i];
        if( counts_arr[ind] >= 1 ) { // indexing and counting found elements
            counts_arr[ind] = counts_arr[ind] + 1;
        } else {
            counts_arr[ind] = 1;
        }
    }
 
    for ( ind in counts_arr ) {
        if ( counts_arr[ind] > 1 ) { // duplicates - it's the elements found more than once
            duplicates_arr.push(ind);
        }
    }
 
    //alert( ' input array = [ ' + input_arr + ' ]; \n duplicates array =   [ ' + duplicates_arr + ' ];' ); // alert for demonstation
    document.getElementById('log').innerHTML = ' input array = [ ' + input_arr + ' ]; \n duplicates array =   [ ' + duplicates_arr + ' ];';
    // return duplicates_arr;
}
 
find_duplicates_array( arr );

Leave a Reply

Your email address will not be published. Required fields are marked *