469,931 Members | 1,799 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,931 developers. It's quick & easy.

Non Unique Values in Array

1
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
Feb 24 '08 #1
1 1561
hsriat
1,654 Expert 1GB
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;

Expand|Select|Wrap|Line Numbers
  1. function getMostlyFoundStringInArray(arr) {
  2.     var reps = new Array;    //array in the form of Value=> NoOfRepetitions
  3.     for (var i=0; i<arr.length; i++) reps[arr[i]] = 0;
  4.     for (i=0; i<arr.length; i++) reps[arr[i]]++;
  5.     if (reps.length!=1)
  6.         for (i=1; i<arr.length; i++)
  7.             var result =  reps[arr[i]] > reps[arr[i-1]] ? arr[i] : arr[i-1];
  8.     else return arr[0]+'='+arr.length;
  9.     return result+'='+reps[result]; //slice across '=' and use required value , [0] will be the value, [1] will be no of repetitions.
  10. }
  11.  
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.
Feb 24 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Peter N. Schweitzer | last post: by
1 post views Thread by jason | last post: by
1 post views Thread by Joep | last post: by
8 posts views Thread by nescio | last post: by
5 posts views Thread by Paulers | last post: by
9 posts views Thread by Brian Tkatch | last post: by
1 post views Thread by Chuy08 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.