Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

teeny array

Status
Not open for further replies.

veevee

Programmer
Dec 12, 2000
15
CA
I would like to loop through a simple array to count the number of double elements. I've started (below) but only run through the first set. I need a little guidance in how I could have it increment further.

var chars = new Array("a", "a", "b", "b", "c", "d", "c","a");
var doubles= 0;

for (x= 0; x<charsLen; x++){
for (i = 1; i< charsLen; i++){
if (characters[x] == characters){
doubles ++;
}
}
}
...
 
Try:

var chars = new Array(&quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;c&quot;,&quot;a&quot;);
var doubles= 0;

for (x= 0; x<charsLen-1; x++)
{
for (y = x; y< charsLen; y++)
{
if (chars[x] == chars[y])
{doubles++;}
}
}


This will NOT produce accurate results for triples, though. Using this routine will give you a match for a double for chars[0]/chars[1], chars[0]/chars[7], and chars[1]/chars[7] pairs. Is this what you want?
 
It's giving me a result of '12' doubles. Which can't be true for the array given.
I would only like to indicate if an element is repeated for now.
 
It's giving me a result of '12' doubles. Which can't be true for the array given.
I would only like to indicate if an element is repeated for now.
 
It's giving me a result of '12' doubles. Which can't be true for the array given.
I would only like to indicate if an element is repeated for now.
 
It's giving me a result of '12' doubles. Which can't be true for the array given.
I would only like to indicate if an element is repeated for now.
 
It's giving me a result of '12' doubles. Which can't be true for the array given.
I would only like to indicate if an element is repeated for now.
 
This would show any multiples at all:

var chars = new Array(&quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;c&quot;,&quot;a&quot;);
var doubles=new Array(), dindex=0;


for (var x=0; x<chars.length-1; x++)
{
for (var y=x+1; i< chars.length; y++)
{
if (chars[x] == chars[y])
{
var doubled=false;
for (var di=0;di<doubles.length;di++)
{
if (chars[x]==doubles[di])
{doubled=true; break;}
}
if (doubled==false)
{doubles[dindex]=chars[x]; dindex++;}
}
}
}

After this, doubles.length gives you the number of values in the original array that are repeated, and the array doubles has all of the values that are repeated in the array.
 
Thanks again.
That's it, I can work with that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top