Sorry for the weird title, not sure how to describe it in one sentence. What I am trying to do is build a script that will read through an array of words and compare another word to the list to find where it would be placed alphabetically; between which two words would my word go.

Here is what I have come up with so far which doesn't work with words shorter than the shortest word in my list, or words spelled like the shortest word in my list except having a few more characters, plus more various issues.

Example: My list

ape
apple
attack
awol

If I use keywords "apex," or "as", this script fails. What can I do to fix my code... I am stumped!

<html>
<head>
<script>
var tests=new Array("ape","apple","attack","awol");
function find_hole(str)
{
	var i=0;
	var x=0;
	var c1=0;
	var c2=0;
	var c3=0;
	for(x=0;x<tests.length;x++)
	{
		for(i=0;i<str.length;i++)
		{
			c1=str.substring(i,1);
			c2=tests[x].substring(i,1);
			if(x+1<tests.length)
			{
				c3=tests[x+1].substring(i,1);
			}
			if(c1>c2&&c1<c3)
			{
				return x;
			} else if(c1<c2)
			{
				return 0;
			}

		}
	}
	return x;
}
</script>
</head>
<body>
<script>
	var nmatch=0;
	var keyword="ass";
	nmatch=find_hole(keyword);
	if(nmatch==0) {
		alert("A hole for " + keyword + " is before " + tests[nmatch]);
	} else if(nmatch==tests.length)
	{
		alert("A hole for " + keyword + " is after " + tests[nmatch-1]);
	} else
	{
		alert("A hole for " + keyword + " is between " + tests[nmatch] + " and " + tests[nmatch+1]);
	}
</script>
</body>
</html>

Sorry, I figured it out:

<html>
<head>
<script>
var tests=new Array("ape","apple","attack","awol","bowl","brick");
function add_item(str)
{
	tests.push(str);
	tests.sort();
}
</script>
</head>
<body>
<script>
	var keyword="aztec";
	add_item(keyword);
	alert(tests);
</script>
</body>
</html>

This is so much easier!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.