Sorting arrays in Javascript

Let’s suppose we have a simple array containing 5 strings. The .sort() method sorts them in ascending order and the .reverse() method sorts them in descending order, as demonstrated below.

var simpleArray1 = ["Paul", "Peter", "Mary"];

// .sort() will sort the array to become "Mary", "Paul", and then "Peter".
simpleArray1.sort();

// .reverse() will sort the array to become "Peter", "Paul", and then "Mary".
simpleArray1.reverse();

In the case of numbers, we should be aware that they are sorted in a similar fashion as strings. In the following example, 100 appears before 32 when using .sort() because 1 comes before 3.

var simpleArray2 = [100, 999, 32];

// .sort() will sort the array to become 100, 32, and then 999.
simpleArray2.sort();

// .reverse() will sort the array to become 999, 32, and then 100.
simpleArray2.reverse();

To sort an array of numbers by their numeric values, we should pass in a function into the .sort() method as follows.

// .sort(function(a, b) {return a - b}) will sort the array to become 32, 100, and then 999.
simpleArray2.sort(function(a, b) {return a - b});

// .sort(function(a, b) {return b - a}) will sort the array to become 999, 100, and then 32.
simpleArray2.sort(function(a, b) {return b - a});

We can sort an array of objects, ie. each element of the array has its own set of properties, on any of the properties as well. In the following example, each object in the array has a property called “id”, which we are using to sort.

// Ascending order
complexArray.sort(
	function(a, b) {
		return (a.id > b.id ? 1 : (a.id < b.id ? -1 : 0));
	} 
);

// Descending order
complexArray.sort(
	function(a, b) {
		return (a.id > b.id ? -1 : (a.id < b.id ? 1 : 0));
	} 
);

Javascript delay function

The sample Javascript delay() function below performs a delay for X milliseconds. During the time specified, users can proceed to perform actions on the particular web page.

Quick reminder: 1000 milliseconds = 1 second, 60000 milliseconds = 1 minute

function delay(milliseconds) {
	var cmd = 'alert("Hello World!  This should have appeared after ' + milliseconds + ' milliseconds.");';
	setTimeout(cmd, milliseconds);
}

Below is a live example, followed by the HTML/Javascript code used.



<script type="text/javascript">
function delay(milliseconds) {
	var cmd = 'alert("Hello World!  This should have appeared after ' + milliseconds + ' milliseconds.");';
	setTimeout(cmd, milliseconds);
}
</script>
<input type="button" onclick="javascript: delay(3000);" value="Do a 3-second delay">

If you are looking for a way to “freeze” the browser during the wait time, try the Javascript pause() method.

Javascript pause function

The sample Javascript pause() function below performs a pause for X milliseconds. During the time specified, the browser would appear “frozen” to the user.

Quick reminder: 1000 milliseconds = 1 second, 60000 milliseconds = 1 minute

function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

Below is a live example, followed by the HTML/Javascript code used.



<script type="text/javascript">
function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

function preStuff() {
	alert('This is before the 3-second pause');
}

function postStuff() {
	alert('This is after the pause; it should have been paused for 3 seconds');
}

</script>

<input type="button" onclick="javascript: preStuff(); pause(3000); postStuff();" value="Do a 3-second pause">

If you are looking for a way to simply delay execution of code without "freezing" the browser during the wait time, try the Javascript delay() method.

Using Javascript to manipulate HTML select-dropdown boxes

First, let us establish a sample select object as below. The Javascript object “objSelect” will also be established to refer to this HTML object.


<select id="colors">
	<option value="r">Red</option>
	<option value="g">Green</option>
	<option value="b">Blue</option>
</select>

<script type="text/javascript">
var objColors = document.getElementById("colors");
</script>

The following Javascript code can be used to display which option has been selected by the user. If you choose “Blue”, for example, you will get alert dialogues “b”, “Blue”, and then “2”.

alert(objColors.value); // Display the value; in this example, red is "r", green is "g", and blue is "b"
alert(objColors.options[objColors.selectedIndex].text); // Display the text; in this example, "red", "green", and "blue"
alert(objColors.selectedIndex); // Display the index number; in this example, red is 0, green is 1, and blue is 2

The following Javascript code provides you the means to add a new option to the HTML select object. “Yellow” is going to be added to the end of the list, and “White” is going to be added as the third choice.

var newOption1 = document.createElement('option');
newOption1.text = "Yellow";
newOption1.value = "y";

var newOption2 = document.createElement('option');
newOption2.text = "White";
newOption2.value = "w";

try {
	// For standard browsers
	objColors.add(newOption1, null);
}
catch (ex) {
	// For Microsoft Internet Explorer and other non-standard browsers.
	objColors.add(newOption1);
}

try {
	// For standard browsers
	objColors.add(newOption2, objColors.options[2]);
}
catch (ex) {
	// For Microsoft Internet Explorer and other non-standard browsers.
	objColors.add(newOption2, 1);
}

The code below removes an option. The first example removes index #1, or the second option. The second example removes whatever the last option is.

objColors.remove(1); // Removes index #1, or "Green" in our original example.
objColors.remove(objColors.length-1); // Removes whatever the last option is.

Finally, the code below selects a particular option.

< pre class="code">
objColors.options[1].selected = true; // Selects the second option, or “Green” in our original example

You may see the running examples below.





Complete code to the running examples is shown below.


<select id="colors">
	<option value="r">Red</option>
	<option value="g">Green</option>
	<option value="b">Blue</option>
</select><br /><br />
<input type="button" value="check current choice" onclick="check();"><br />
<input type="button" value="add" onclick="add();"><br />
<input type="button" value="remove second option" onclick="remove();"><br />
<input type="button" value="remove last option" onclick="removeLast();"><br />
<input type="button" value="select" onclick="selected();"><br />

<script type="text/javascript">
var objColors = document.getElementById("colors");


function check() {
	alert(objColors.value); // Display the value; in this example, red is "r", green is "g", and blue is "b"
	alert(objColors.options[objColors.selectedIndex].text); // Display the text; in this example, "red", "green", and "blue"
	alert(objColors.selectedIndex); // Display the index number; in this example, red is 0, green is 1, and blue is 2

}

function add() {
	var newOption1 = document.createElement('option');
	newOption1.text = "Yellow";
	newOption1.value = "y";

	var newOption2 = document.createElement('option');
	newOption2.text = "White";
	newOption2.value = "w";

	try {
		// For standard browsers
		objColors.add(newOption1, null);
	}
	catch (ex) {
		// For Microsoft Internet Explorer and other non-standard browsers.
		objColors.add(newOption1);
	}

	try {
		// For standard browsers
		objColors.add(newOption2, objColors.options[2]);
	}
	catch (ex) {
		// For Microsoft Internet Explorer and other non-standard browsers.
		objColors.add(newOption2, 2);
	}
}

function remove() {
	objColors.remove(1); // Removes index #1, or "Green" in our original example.
}

function removeLast() {
	objColors.remove(objColors.length-1); // Removes whatever the last option is.
}

function selected() {
	objColors.options[1].selected = true;
}
</script>

Custom trim() functions in Javascript

I come from a database background, so I have always taken Oracle’s trim() functions for granted. In short, the trim() function removes spaces at the start and end of a string, the ltrim() function removes spaces at the start (ie. left side) of a string, and finally the rtrim() function removes spaces at the end (ie. right side) of a string. As I dabble into web development nowadays, I thought it would be handy to have similar functions in Javascript at my disposal.

function trim(txt) {
	return txt.replace(/^s+|s+$/g,"");
}


function ltrim(txt) {
	return txt.replace(/^s+/,"");
}


function rtrim(txt) {
	return txt.replace(/s+$/,"");
}

Below are some usage examples.

alert(trim(' hello '));
// This should return 'hello'; spaces on both sides is removed

alert(ltrim(' hello '));
// This should return 'hello '; only space on left side is removed

alert(rtrim(' hello '));
// This should return ' hello'; only space on right side is removed

Convert text to upper or lower case

To do so, simply make use of the toUpperCase() or toLowerCase() methods. For example:

<input type="text" name="myField" id="myField" size="20" onKeyup="javascript:this.value=this.value.toUpperCase();"> : To Upper

<input type="text" name="myField" id="myField" size="20" onKeyup="javascript:this.value=this.value.toLowerCase();"> : To Lower

Below is the working sample:

 To Upper

 To Lower

If you do not wish to run it for each key-up such as in this example, try the onChange event, which will only fire when the user leaves the input field.

Lorem ipsum automatic text generator in Javascript

First, create a Javascript file that we will call “lorem.js”. Copy/paste the following code into that file.


// Lorem ipsum generator
// @author C. Peter Chen of http://dev-notes.com
// @date 20080812
function loremIpsum(elem) {
	var loremIpsumWordBank = new Array("lorem","ipsum","dolor","sit","amet,","consectetur","adipisicing","elit,","sed","do","eiusmod","tempor","incididunt","ut","labore","et","dolore","magna","aliqua.","enim","ad","minim","veniam,","quis","nostrud","exercitation","ullamco","laboris","nisi","ut","aliquip","ex","ea","commodo","consequat.","duis","aute","irure","dolor","in","reprehenderit","in","voluptate","velit","esse","cillum","dolore","eu","fugiat","nulla","pariatur.","excepteur","sint","occaecat","cupidatat","non","proident,","sunt","in","culpa","qui","officia","deserunt","mollit","anim","id","est","laborum.","sed","ut","perspiciatis,","unde","omnis","iste","natus","error","sit","voluptatem","accusantium","doloremque","laudantium,","totam","rem","aperiam","eaque","ipsa,","quae","ab","illo","inventore","veritatis","et","quasi","architecto","beatae","vitae","dicta","sunt,","explicabo.","nemo","enim","ipsam","voluptatem,","quia","voluptas","sit,","aspernatur","aut","odit","aut","fugit,","sed","quia","consequuntur","magni","dolores","eos,","qui","ratione","voluptatem","sequi","nesciunt,","neque","porro","quisquam","est,","qui","dolorem","ipsum,","quia","dolor","sit,","amet,","consectetur,","adipisci","velit,","sed","quia","non","numquam","eius","modi","tempora","incidunt,","ut","labore","et","dolore","magnam","aliquam","quaerat","voluptatem.","ut","enim","ad","minima","veniam,","quis","nostrum","exercitationem","ullam","corporis","suscipit","laboriosam,","nisi","ut","aliquid","ex","ea","commodi","consequatur?","quis","autem","vel","eum","iure","reprehenderit,","qui","in","ea","voluptate","velit","esse,","quam","nihil","molestiae","consequatur,","vel","illum,","qui","dolorem","eum","fugiat,","quo","voluptas","nulla","pariatur?","at","vero","eos","et","accusamus","et","iusto","odio","dignissimos","ducimus,","qui","blanditiis","praesentium","voluptatum","deleniti","atque","corrupti,","quos","dolores","et","quas","molestias","excepturi","sint,","obcaecati","cupiditate","non","provident,","similique","sunt","in","culpa,","qui","officia","deserunt","mollitia","animi,","id","est","laborum","et","dolorum","fuga.","harum","quidem","rerum","facilis","est","et","expedita","distinctio.","Nam","libero","tempore,","cum","soluta","nobis","est","eligendi","optio,","cumque","nihil","impedit,","quo","minus","id,","quod","maxime","placeat,","facere","possimus,","omnis","voluptas","assumenda","est,","omnis","dolor","repellendus.","temporibus","autem","quibusdam","aut","officiis","debitis","aut","rerum","necessitatibus","saepe","eveniet,","ut","et","voluptates","repudiandae","sint","molestiae","non","recusandae.","itaque","earum","rerum","hic","tenetur","a","sapiente","delectus,","aut","reiciendis","voluptatibus","maiores","alias","consequatur","aut","perferendis","doloribus","asperiores","repellat");
	var minWordCount = 15;
	var maxWordCount = 100;

	var randy = Math.floor(Math.random()*(maxWordCount - minWordCount)) + minWordCount;
	var ret = "";
	for(i = 0; i < randy; i++) {
		var newTxt = loremIpsumWordBank[Math.floor(Math.random() * (loremIpsumWordBank.length - 1))];
		if (ret.substring(ret.length-1,ret.length) == "." || ret.substring(ret.length-1,ret.length) == "?") {
			newTxt = newTxt.substring(0,1).toUpperCase() + newTxt.substring(1, newTxt.length);
		}
		ret += " " + newTxt;
	}
	document.getElementById(elem).innerHTML = document.getElementById(elem).innerHTML + "<p>Lorem ipsum " + ret.substring(0,ret.length-1) + ".</p>";
}

Next, in your HTML page, include the Javascript file as follows.


<script type="text/javascript" src="lorem.js"></script>

To populate some random text, call the Javascript function “loremIpsum(‘elementName’)”, where “elementName” is the ID of an element you wish to populate the text to. The following code illustrate how we can use this function to populate automatic lorem ipsum text into a DIV.


<html>
<head>
<script type="text/javascript" src="lorem.js"></script>
</head>
<body>

<p><b>Lorem Ipsum generator</b><br />
Written by C. Peter Chen of <a href="http://dev-notes.com">dev-notes.com</a></p>

<div id="div1">
</div>

<input type="button" onclick="loremIpsum('div1');" value="Add Text">

</body>
</html>

Finally, the following section is a live demo of how the code should behave.

Get current mouse cursor position with Javascript

The Javascript code below provides a sample of how the user’s mouse cursor position, displayed as X- and Y-coordinates in relation to the top left corner of the page. In this example, I put the X- and Y-coordinate values in an input box, but you can tweak that to fit your needs.


<html>

<script type="text/javascript">
window.onload = init;
function init() {
	if (window.Event) {
	document.captureEvents(Event.MOUSEMOVE);
	}
	document.onmousemove = getCursorXY;
}

function getCursorXY(e) {
	document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
</script>

<body>

<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor

</body>
</html>

Below is a demo of the code listed above:

X-position of the mouse cursor

Y-position of the mouse cursor