0

Please how can I get the duplicated value from an array ?

Ex: Array [10,3,10,10]
display that we have 3 duplicated in location 1,3 and 4

Regards

I have tried this one :

 q = new Array();
                q = [A, B, C, D];

                qValue = function (array) {
                equal = array[0];
                for (j=0; j<array.length; j++) {
                if (array[j]===equal) {
                equal = array[j];
                }
                }
                return equal;
                };
                trace(qValue(q));
4

1 回答 1

1

Something like this should work:

var array:Array = [1,2,3,4,3];

// create a dictionary and go through our array pulling out the keys
var dict:Dictionary = new Dictionary();
for each( var i:int in array )
{
    if( i in dict ) // checks if the number is already in our dict as a key
        dict[i]++;
    else
        dict[i] = 1;
}

// now go through our dictionary, finding the duplications
for( var key:* in dict )
{
    var num:int = dict[key];
    if( num == 1 )
        continue; // single value - ignore
    trace( "We have " + num + " occurrences of " + key );
}

Edit

To also have the locations (indicies) of the repeated values, use this instead:

var array:Array = [1,2,3,4,3];

// create a dictionary and go through our array, pulling out the values
var dict:Dictionary = new Dictionary();
var len:int         = array.length;
for( var i:int = 0; i < len; i++ )
{
    var val:int = array[i]; // get the value from the array
    if( !( val in dict ) )  // if it's not in our dictionary, create a new array
        dict[val] = [];
    dict[val].push( i );    // add the index of the value to the array
}

// now go through our dictionary, finding the duplications
for( var key:* in dict )
{
    var indicies:Array = dict[key];
    if( indicies.length <= 1 )
        continue; // single value - ignore
    trace( "The value " + key + " is repeated " + indicies.length + " times. Indicies: " + indicies );
}

Edit - AS2 no "if in"

Add the function:

function _getArray( obj:Object, val:Number ):Array
{
    // try and find the one already created
    for( var key:* in obj )
    {
        if( key == val )
            return obj[val];
    }

    // make a new one
    var a:Array = [];
    obj[val] = a;
    return a;
}

Your array loop should now read

for( var i:int = 0; i < len; i++ )
{
    var val:int = array[i]; // get the value from the array
    var occurrenceArray = _getArray( obj, val ); // obj = dict
    occurrenceArray.push( i ); //  add the index of the value to the array
}
于 2013-06-19T12:32:52.177 回答