CodingBison

This page takes a look at some of the basic methods provided by Array.prototype: sort(), reverse(), slice(), indexOf, lastIndexOf. These methods help us sort, format, and search arrays.

Basic Methods: sort, reverse, and slice

The first method in the above set, sort() arranges an array in ascending order, as they would appear in a dictionary. If the array elements are numbers, then JavaScript first converts these numbers into strings and then, sorts them in alphabetical order. sort() sorts the array in place; in other words, it does not create a new array with sorted values, but instead, it simply reorders the elements of the passed array to sort them.

The second method in the above set, reverse() reverses the passed array; in other words, the first element becomes the last element, the second element becomes the second element from last, and so on. This method reverses the array in place and does not return a new array.

The next method in the above set, slice(), returns a slice of the passed array. It takes two indexes as arguments: startIndex and lastIndex. The sliced array contains all the elements starting at the startIndex and up to (but not including) endIndex. If we do not specify the second argument, then slice() returns the entire sub-array starting at startIndex and containing all the remaining elements.

For slice(), we can also specify these indexes as negative indexes. When it is specified negative, then it is counted from the reverse. Thus slice(0,-1) means that we should return a sub-array that starts at index 0 and contains all elements up to (but not including) the last element.

Let us go through a simple example that demonstrates usage of these methods. This example uses a function printArray() to print elements of the array;

 <!doctype html>
 <html>
 <div id="idDiv"></div>

 <script type="text/javascript"> 
 // Get a handle of the div element.
 var elem = document.getElementById("idDiv");

 // Function to print array elements.
 function printArray(passedArray) {
     for (var i = 0; i < passedArray.length; i++) {
         elem.innerHTML += passedArray[i]; 
         if (i != (passedArray.length - 1)) {elem.innerHTML += ", ";}
     }
 }

 // Define an array and print it. 
 var arraySample = ["Merlin", "Unicorn", "Goblins", "Dragon", "Phoenix"];
 elem.innerHTML += "arraySample: ";
 printArray(arraySample);

 // Sort the array.
 arraySample.sort();
 elem.innerHTML += "<br>arraySample after sorting: ";
 printArray(arraySample);

 // Reverse the array. 
 arraySample.reverse();
 elem.innerHTML += "<br>arraySample after reversing: ";
 printArray(arraySample);

 // Print some elements using slice.
 elem.innerHTML += "<br>arraySample.slice(2,3): " + arraySample.slice(2,3) + "<br>";
 elem.innerHTML += "arraySample.slice(0,-2): " + arraySample.slice(0,-2) + "<br>";
 </script>
 </html>

We provide its output below. Note that since sort() and reverse() arrange elements of arraySample in place, subsequent steps get to see a reordered array instead of the original.



Figure: Basic Methods for Arrays

Let us understand the sort() method a little bit more.

By default, sort() arranges array elements as they appear in the dictionary. Thus, if we have an array as: "var arrraySample = [101, 15, "Unicorn", "Phoenix"];", then sort() would rearrange it as "[101, 15, "Phoenix", "Unicorn"];". Clearly, it is okay for "101" to appear before "15" as per the dictionary order. However, if we were to treat these as numbers, then we would have expected 15 to appear before 101.

For such cases, we we can provide a user-defined callback function as an optional argument to sort(); the callback function can take up-to two arguments and the sort() method uses these arguments to compare two consecutive elements of the array. The sort() method uses this function to determine the result of passing any two consecutive elements and uses the return value (positive, negative, or zero) to accordingly arrange the two elements. If the first element is greater than the second and if the callback returns a positive value, then sort() keeps the first element before the second element. On the other hand, if the callback returns a negative value, then sort() keeps the second element before the first element.

Let us go through a simple example (provided below) that passes a user-defined callback function ("userFunc") to the sort() method. With this, we see that 15 does appear before 101.

 <!doctype html>
 <html>
 <script type="text/javascript"> 

 // A user defined callback function.
 var userFunc = function (x1, x2) {return (x1-x2)};

 var a = [101, 15, "Unicorn", "Phoenix"];

 a.sort();         //a becomes [101, 15, "Phoenix", "Unicorn"];
 a.sort(userFunc); //a becomes [15, 101, "Phoenix", "Unicorn"];

 </script>
 </html>

In the above example, if userFunc() were to always return a value of -1 as in "userFunc = function () {return (-1)};", then sort() would simply keep elements the way they are since with this the any element would always be considered smaller than its next element. Conversely, if the function were to always return a value of 1 as in "userFunc = function () {return (1)};", then sort() would simply reverse the elements!

Basic Methods: indexOf and lastIndexOf

Now, we discuss the last two methods that help us search a given element within an array: indexOf() and lastIndexOf(). Both of these methods take an element as argument and return the index of its first occurrence. indexOf() starts the search from the beginning of the array and progresses towards the end of the array. On the other hand, lastIndexOf() starts its search at the end of the array and progresses towards the beginning of the array.

If either of these methods do not find the passed element, then they return a value of -1.

Both of these methods also take an optional second argument that indicates the starting index for the search. This can be an important feature for a large arrays, where one might do a lookup for an element in several rounds. After each round, one can store the index of the occurrence and pass that as a starting index for the next round.

The second argument (the starting index) could also be an negative index. When it is specified as a negative value, then the starting index for search is counted from the reverse.

Let us look at a simple example that presents usage for both indexOf() and lastIndexOf() methods.

 <!doctype html>
 <html>
 <script type="text/javascript"> 

 // Define a simple array.
 var arraySample = ["Merlin", "Unicorn", "Goblins", "Merlin", "Goblins", "Gandalf"];
 var index = 0;

 index = arraySample.indexOf("Goblins");        // index is 2.
 index = arraySample.indexOf("Goblins", 3);     // index is 4.
 index = arraySample.lastIndexOf("Merlin");     // index is 3.
 index = arraySample.lastIndexOf("Merlin", -4); // index is 0.
 index = arraySample.lastIndexOf("Griffin");    // index is -1.

 </script>
 </html>




comments powered by Disqus