Looking for the previous guiStuff?

It's still here, the content didn't go anywhere. You may want to check out this new guiStuff though -- It's rather informative.

References/Tutorials:


Intro Documents:


guiStuff:






::Stuff for the multi-spec coder;

Coding, formats, standards, and other practical things.

 Home  //  JavaScript  //  Arrays: Part 3 - Array Methods 2 

<!-- JavaScript

Arrays: Part 3 - Array Methods 2

In Part 2, we left off discussing ways to create pseudo-structures using the available Array methods. In this article, we'll cover Array/String methods, as well as the involved splice() method, and ways of creating your own functions for dedicated-purpose functionality.

The Array/String Methods

The Array Class defines the join() method, which, unlike most Array methods, returns a String Object. As well, the String object defines the method split() which returns an Array of Strings from a single String Object. The two methods are virtually opposites of each other, in terms of their function.

join()

The join() method is kind of like the practical version of the Array class's toString(). Instead of taking the values of the Array and concatenating them, as Strings, separated always by commas, join() allows you to choose which delimiter it will use to separate the Strings.

As mentioned, join() already returns a String value, so it may be passed along to alert() directly:

var myArr = ["Hydrogen", "Helium", "Lithium", "Beryllium", "Boron"]; alert(myArr.join("-")); // alerts 'Hydrogen-Helium-Lithium-Beryllium-Boron'

What join() has in common with the Array class's toString() method is that it calls the particular toString() method for every individual element within the Array, so keep this in mind when handing non-String values to join():

var myArr = [true, 0, 1, 2, 0xE]; alert(myArr.join("-")); // alerts 'true-0-1-2-3.14-15'

The Boolean value 'true' returned the String "true", and not the number 1, as some methods would produce. The hexadecimal value of 0xF returned the String value of "14", because it was first converted into a decimal value, and then converted into a String primitive.

The delimiter may be of any length, not just one character:

var myArr = [1, 2, 3, 4]; alert(myArr.join(", and ")); // alerts '1, and 2, and 3, and 4'

The join() method can be used to 'encode' arrays into String values to prepare them for storage as one long byte string. For example, you may want to use a delimiter like |, after you've made sure that none of the values in the Array contains that character, and then concatenate all of the Array's values separated by the | character. You might then send this String to a server-side script for storage and/or handling, and could receive it back to be split back into an Array using the split() method.

split()

The split() method is a very powerful method of the String class. It takes one argument, a String value, and returns an Array Object. The String on which it's applied is split into substrings which are placed into elements within the resulting Array. The String which is provided as the argument determines what the delimiter to split the String with will be.

For example:

var myStr = "one|two|three|four"; var myArr = myStr.split("|"); alert(myArr.toString()); // alerts 'one,two,three,four'

The Delimiter itself is removed from the String entirely.

If the delimiter happens to appear right at the beginning of the String, then the first element of the Array will be an empty String. As well, if the delimiter appears at the end of the String, then the last element of the Array will be an empty String:

var myStr = "|one|two|three|four|"; var myArr = myStr.split("|"); alert(myArr.toString()); // alerts ',one,two,three,four,'

A common use for split() is to simply devide a sentence into words. You would do this by deviding the String using the space (" ") delimiter:

var myStr = "The quick brown fox jumped over the jazy dog"; var myArr = myStr.split(" "); alert(myArr.toString()); // alerts 'The,quick,brown,fox,jumped,over,the,jazy,dog'

The reason why this is very useful is, apart from the obvious uses in parsing sentences in order to count words and match phrases by iteration, is that it allows what is sometimes referred to as the Array via String definition. Suppose you have a long list of words that are constants, like the greek alphabet. If you were to define it using the normal Array declaration, how many characters would be wasted on quotes and commas? Instead, you can do this:

var myArr = "Alpha Beta Gamma Delta Epsilon Zeta Eta Theta Iota".split(" "); alert(myArr.toString()); // alerts 'Alpha,Beta,Gamma,Delta,Epsilon,Zeta,Eta,Theta,Iota'

There's nothing preventing you from using any other delimiter, of course. Suppose you were listing dog breeds, and you wanted to list 'Golden Retriever' and 'German Shepherd'; In that case, using the space character as the delimiter wouldn't work, so you might use a comma, or a character that you knew for certain woulnd't appear in any of the constants, like a plus sign (+).
This is often used to compact code, as well as make it more convenient, at times, to write it.

An interesting feature of the split() method is the ability to accept an emptry String as a delimiter. If it receives an empty String, it will split the string into its individual characters, and place one into each Array element:

var myStr = "example"; var myArr = myStr.split(""); alert(myArr.toString()); // alerts 'e,x,a,m,p,l,e'

Remember that Strings in JavaScript are kept in 16-bit dynamic arrays internally, so in a sense, JavaScript is converting one type of Array into another. The two types of Arrays are completely different, however, since where Strings hold 16 bits of data at every index, Arrays contain an Object of variable size (not to mention type) within each element.

splice()

Arguably the most complicated method in the Array class is splice(). It is also extremely versetile and allows you to use it to construct other functions which use splice() in a specific manner to achieve a more vertical goal. First, unlike the slice() method, splice() effects the Array directly. It can be used to insert items, remove items, or do both at the same time.

What makes splice() special is that, while it technically takes either two or three arguments, the 'third' argument may be composed of multiple values. This doesn't mean that the third argument is an Array, it's simply that splice() will accept any number of arguments, and treat any argument from the third one onward as part of a 'list' of arguments that make up the third argument. It's actually simpler than it sounds:
The first argument that splice() takes is the starting point (the index within the Array) at which it will begin its operation. It doesn't matter what operation that will be, the first argument will always tell splice() where that operation will begin. The second argument determines how many elements splice() will remove from the Array; It will remove that number of elements from the Array, starting at the index indicated by the first argument.
At this point, you can place a separator, since splice() can simply be used for this operation alone. If splice() is given two arguments, it will remove n elements from the Array, starting at the index indicated by the first argument, where n is the number passed as the second argument.
After the second argument, if you supply splice() with additional arguments, they may be of any data type. That is to say, from the third argument onward, you may pass splice() any number of values, of any type of data. It will insert these values into the Array, in the order in which they were passes, at the position indicated by the first argument. The removal of items, if it occurs (you may choose to remove 0 items), has no bearing on this addition process. That is to say, even if you choose to remove items from the Array, the first argument will still serve as the index from which to start adding these new values.

Let's see a few examples:

var myArr = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]; myArr.splice(2, 2); alert(myArr.toString()); // alerts 'Alpha,Beta,Epsilon' myArr.splice(2, 0, "Gamma", "Delta"); alert(myArr.toString()); // alerts 'Alpha,Beta,Gamma,Delta,Epsilon' myArr.splice(1, 3, "Zeta"); alert(myArr.toString()); // alerts 'Alpha,Zeta,Epsilon'

First, an Array is defined with the greek letters Alpha through Epsilon. Then splice() is called and given two arguments: 2, and 2. It goes to index 2 of the Array, where it finds 'Gamma', and then removes two elements -- the element at index 2, and the element located at the following index. The resulting Array now contains: 'Alpha,Beta,Epsilon'.
At this point, splice() is called again, this time with four arguments. The first argument is 2, the second is 0, and the third and fourth arguments are 'Gamma' and 'Delta', respectively. It thus goes to index 2 of the Array, but this time, it's told to remove 0 elements, so it skips the removal process. It then looks at the third argument and onward, and 'sees' two String values. It therefor places these two String values starting at index 2, in the order in which they were given. Note that it simply 'makes room' for them by pushing the rest of the Array elements forward, so that if you added 2 new values, it would 'push' the rest of the elements following these values 'up' the Array by 2 (that is, each alement after the starting index will first be relocated to an index incremented by 2). The resulting Array is the initial Array: The letters Alpha through Epsilon.
The third time splice() is called, it's given three arguments: 1, 3, and the String value 'Zeta'. First it goes to index 1, and removes 3 elements. This operation is separate, think of it as two function calls. Internally, the Array now holds 'Alpha' and 'Epsilon'. It now looks at the third argument (and onward) to find one String value: 'Zeta', which it then places at the index which was specified by the first argument: index 1. The Array now contains the values: 'Alpha,Zeta,Epsilon'.

As if that wasn't enough to make splice() a veritable Swiss Army Knife, there's even more: splice() returns everything that it removes as an Array Object. Here's what would happen if I took the functions performed above, and alerted the direct result of these functions treated as Arrays (by calling their toString() method):

var myArr = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon"]; alert(myArr.splice(2, 2).toString()); // alerts 'Gamma,Delta' alert(myArr.splice(2, 0, "Gamma", "Delta").toString()); // alerts '' alert(myArr.splice(1, 3, "Zeta").toString()); // alerts 'Beta,Gamma,Delta'

The first time splice() is called it removed two elements, 'Gamma' and 'Delta', and so it returned a 2-element-long Array Object with those values. The second time it was called it didn't remove any elements, so it returned an empty Array Object. The third time it was called it removed three values: 'Beta,Gamma,Delta', which was the contents of the Array it returned.

The splice() method allows you to create an amazing amount of specific, dedicated-purpose functions to use on your Arrays. You may use it within one function simply to remove n elements from a certain index, in which case you'd only be using two arguments. In another function, you may choose to use it to replace two sequential values with two new ones, in which case you'd always call splice() with four total arguments, and the second argument will always be 2.

Home-Made Array Functions

Creating your own functionality according to your needs will be something you'll probably do a lot with both Arrays and Strings. Here's an example of how you would use the splice() method to create two functions that act on Arrays in a specific manner:

function moveDown(modArray, index){ if(index == 0){return modArray;} modArray.splice(index-1, 2, modArray[index], modArray[index-1]); return modArray; } function moveUp(modArray, index){ if(index > modArray.length-2){return modArray;} modArray.splice(index, 2, modArray[index+1], modArray[index]); return modArray; }

Within applications, you will often have the ability to edit a list of items, and one of those abilities will be to move items up and down the list. These two functions provide this functionality for Arrays. You supply them with the Array you're working on, and the index you'd like to move. You'd call moveDown() to move an Array element down by one index, basically replacing its value with the value of the element located at the index below it. On the other hand, moveUp() will do the opposite: It will move the value at the indicated index one 'notch' up the list, replacing its value with the value of the element located at the index above it.
Note that both functions do not operate on the Array Object they are given, but rather return a new Array Object with the new values. If you wanted to have the function act on the Array Object itself, you'd normally have to augment the Array class by adding a method, and that's a bit beyond the scope of this article.
Mind that both functions begin by checking that what is asked of them is possible: they check if 'there's room' in the Array to perform the move that's requested of them. If there isn't, they return the unmodified Array. After all, you can't move the element at index 0 any lower.

That's it for Part 3. Think about how you would use Arrays in JavaScript to define other data structures, like Associative Arrays. This is actually rather simple considering the arsenal of methods that the Array class provides you with. Also, always be on the lookout for general-purpose functions that you could add to any program, and collect a 'toolbox' from which you can draw functions as needed -- this will always speed up your development process.





Return to the JavaScript section, or go the to Main page.





Looking for the old guiStuff?

It's still here, the old content didn't go anywhere.