Working with arrays



Create an array in JavaScript

Arrays are JavaScript objects and are created just like any other JavaScript object, with the new keyword.

Arrays in JavaScript are zero-based, which means that the first element in the array is at index zero and the last element is at index Array.length –1.

JavaScript converts the anArray variable to the Array object type. After creating an array, you can access its elements by using square brackets.

The following code demonstrates this:

<body>
<input type="submit" onclick="createArray()" value="Array Create" /><br />
<div id="#div1"> </div>
<script type="text/javascript">
    var createArray = function () {
        var anArray = new Array("soccer", "tennis", "volley");
        document.getElementById("#div1").innerHTML = ("Array elements : " + anArray
            +"<br>"+ "Array element at idex 1 is:" + anArray[1]);
    }
</script>
</body>

Using the length property

The length property provides information on how long the array is and how many elements the array has allocated at the time the property is evaluated.

The following example shows how to access the length property:

<body>
<input type="submit" onclick="arrlength()" value="Length Property" /><br />
<div id="#div1"> </div>
<script type="text/javascript">
    var arrlength = function () {
        var anArray = new Array(5);
        document.getElementById("#div1").innerHTML =
            ("Array Length is : " + anArray.length);
    }
</script>
</body>

Using the concat method

The concat method combines two or more arrays into one array. You can store all the elements from the arrays in a variable after applying the concat property.

The following example shows the concat method:

<body>
<input type="submit" onclick="arrConcat()" value="CONCAT Property" /><br />
<div id="#div1"> </div><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
<script type="text/javascript">
    var arrConcat = function () {
       var sports = new Array('football', 'cricket', 'rugby', 'tennis');
       var moreSports = new Array('soccer', 'hockey');
       var combinedSports = sports.concat(moreSports);
       
       document.getElementById("#div1").innerHTML= 
               ("Array Sports: \n[ " + sports.toString() + "]");
       document.getElementById("#div2").innerHTML = 
               ("Array moreSports: \n[ " + moreSports.toString() + "]");
       document.getElementById("#div3").innerHTML = 
               ("Array combinedSports: \n[ " + combinedSports + "]");
      
 }
</script>
</body>

Using the indexOf and lastIndexOf methods

The indexOf method provides a way to find the index of a known element. The indexOf method accepts two parameters: what to search for and the index at which to begin searching.

To search in descending order from the end to the beginning you can use the lastIndexOf method, which accepts the same parameters.

The following code demonstrates the indexOf and lastIndexOf methods:

<body>
<input type="submit" onclick="indexMethods()" value="IndexOf & lastIndexOf" /><br />
<div id="#div1"> </div><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
<script type="text/javascript">
    var indexMethods = function () {
        var sports = new Array('soccer', 'hockey', 'football', 'cricket','tennis');
        var index = sports.indexOf('football', 0); //starting from beginning 0
        var index2 = sports.lastIndexOf('cricket', -1); //starting from the end -1
        document.getElementById("#div1").innerHTML =
                ("Array Sports is: \n[ " + sports.toString() + "]");
        document.getElementById("#div2").innerHTML =
                ("Index of footboll using indexOf is : " + index);
        document.getElementById("#div3").innerHTML =
                ("Index of footboll using lastIndexOf is : " + index2);
    }
</script>
</body>

Using the join method

The join method joins all the elements in an array into a single string separated by a specified string separator.

The join method accepts a string as a parameter, which is the string used as a delimiter to separate the values in the array. The result is a string of all the elements separated by the string passed into the join method.

The following code demonstrates the join method:

<body>
<input type="submit" onclick="joinMethod()" value="Join Method" /><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
 <!-- JOIN METHOD-->
<script type="text/javascript">
    var joinMethod = function () {
        var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'rugby');
        document.getElementById("#div2").innerHTML =
                ("Array sports is : \n" + "[" + sports.toString() + "]");
        var joined = sports.join(',');
        document.getElementById("#div3").innerHTML =
                ("Join (,) beetwen : \n" + "[" + joined + "]");
    }
</script>
</body>

Using the reverse method

The reverse method reverses the sequence of all elements in the array. The last item becomes the first item in the array.

The following code demonstrates the reverse method

<body>
<input type="submit" onclick="reverseMethod()" value="Reverse Method" /><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
<!-- REVERSE METHOD-->
<script type="text/javascript">
    var reverseMethod = function () {
        var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'rugby');
       
        document.getElementById("#div2").innerHTML =
                ("Array sports is : \n" + "[" + sports.toString() + "]");
        document.getElementById("#div3").innerHTML =
                ("Array sports REVERSED : \n" + "[" + sports.reverse() + "]");
    }
</script>
</body>

Using the sort method

The sort method sequences the items in the array in ascending order. The following code demonstrates the sort method:

<body>
<input type="submit" onclick="sortMethod()" value="Sort Method" /><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
<!-- SORT METHOD-->
<script type="text/javascript">
    var sortMethod = function () {
        var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'rugby');
        sports.sort();
        document.getElementById("#div2").innerHTML =
                ("Array sports is : \n" + "[" + sports.toString() + "]");
        document.getElementById("#div3").innerHTML =
                ("Array sports SORTED : \n" + "[" + sports.sort() + "]");
    }
</script>
</body>

Using the slice method

The slice method takes out one or more items in an array and moves them to a new array. The slice method takes two parameters: the indexes where the slice operation should begin and end.

The following code slice the element between indexes (1,2):

<body>
<input type="submit" onclick="sliceMethod()" value="Slice Method" /><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
<!-- SLICE METHOD-->
<script type="text/javascript">
    var sliceMethod = function () {
        var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'rugby');
        var someSports = sports.slice(1, 2);
        document.getElementById("#div2").innerHTML =
                ("Array sports is : \n" + "[" + sports.toString() + "]");
        document.getElementById("#div3").innerHTML =
                ("Array sports SLICE(1 , 2) or between indexes (1,2) : \n" + "[" + someSports + "]");
    }
</script>
</body>

Using the splice method

The splice method provides a way to replace items in an array with new items. The splice method returns an array containing the items that are spliced out of the source array.

The first parameter is the index in the array where the splice operation should start. The second parameter is the number of items to splice, starting from the index specified in the first parameter.

The following code example shows how to use the splice method:

<body>
<input type="submit" onclick="spliceMethod()" value="Splice Method" /><br />
<div id="#div2"> </div> <br />
<div id="#div3"> </div> <br />
<!-- SPLICE METHOD-->
<script type="text/javascript">
var spliceMethod = function () {
    var sports = new Array('soccer', 'basketball', 'hockey', 'football', 'rugby');
    document.getElementById("#div2").innerHTML =
            ("Array sports is : \n" + "[" + sports.toString() + "]");
    var splicedItems = sports.splice(1, 3, 'golf', 'curling', 'darts');
    document.getElementById("#div3").innerHTML =
        ("Array sports SPLICE(1, 3, 'golf', 'curling', 'darts') : \n" 
          + "[" + splicedItems + "]");
}
</script>

Ads Right