Non Unique Values in Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dirt
    New Member
    • Feb 2008
    • 1

    Non Unique Values in Array

    Hi
    I want to sort an array by non unique Values.
    i have array named xo
    for example with values:

    xo[1]="n";
    xo[2]="n";
    xo[3]="n";
    xo[4]="n";
    xo[5]="u";
    xo[6]="u";
    And i need to do something like this:
    newarr[4]="n";
    newarr[2]="u";

    document.write( "the mostly found string is:"+the Biggest value Of newarr key);

    I try to do something like this, but it didnt work....
    k=xo.length;
    p=new Array();
    xyz=new Array();
    for (i=0; i<k; i++) {
    xyz[i]= xo[i];
    for (j=0; j<k; j++) {
    if (j!=i) {
    if (xo[j] == xyz[i]) {
    if(p[xyz[i]]==undefined){
    p[xyz[i]]=1;}
    else{p[xyz[i]]+=1;}
    d.write(xyz[i]+"---"+i+"---"+p[xyz[i]]+"<br>");
    }
    }
    }
    }

    Sorry for my bad english:P:D
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    In the new array, key can not be equal to the number of times a value repeats!
    Coz more than one value can have same number of repetitions.
    But for the new array, you can make it as keys = the value (of old array) itself and value=number of times that value (of old array) is repeated.
    eg., In the example used by you above, it will be like this:

    newarr['n']=4;
    newarr['u']=2;

    [CODE=javascript]function getMostlyFoundS tringInArray(ar r) {
    var reps = new Array; //array in the form of Value=> NoOfRepetitions
    for (var i=0; i<arr.length; i++) reps[arr[i]] = 0;
    for (i=0; i<arr.length; i++) reps[arr[i]]++;
    if (reps.length!=1 )
    for (i=1; i<arr.length; i++)
    var result = reps[arr[i]] > reps[arr[i-1]] ? arr[i] : arr[i-1];
    else return arr[0]+'='+arr.length ;
    return result+'='+reps[result]; //slice across '=' and use required value , [0] will be the value, [1] will be no of repetitions.
    }
    [/CODE]

    PS: This function may not tell you if more than one values have got equal and maximum repetitions. It will just return one out of them.
    Last edited by hsriat; Feb 24 '08, 07:38 PM. Reason: Change: arr.length to reps.length (Line 5)

    Comment

    Working...