Array Implementation in JavaScript

ADMEC Multimedia Institute > Web Design > Array Implementation in JavaScript

Array will work like a container truck, array can store multiple object in a single variable at time (multiple values in a single variable).

Array starts with 0 index and it is a special variable which can store more then one value, so which can store more then one value at a time that is called Array.

Creation of Arrays in JavaScript

Can be created using Javascript array object constructor.

new Array(size)
new Array(e0, e1, ..., N)

Creating JS Array is easy with using the array literal.

var array-name = [item1, item2, ...];

It consists of two square brackets in which we can add optional array elements separated by a comma.

Array elements can be any type, including number, string, Boolean, null, undefined, object, function, regular expression and other arrays.

Both are same:

var fruits = new Array( "apple", "banana", "mango" );
var fruits = [ "apple", "banana", "mango" ];

For example :

// empty array with no elements
var empty = [];

// array with 2 string elements
var days = ["Tue", "wed"];

// array with elements of different types
var mixed = [false, 2.70, "Hello"];

// elements can be arbitrary expressions
var suffix = "tree";
var trees = ["Oak" + suffix, "Elm" + suffix];

// 2 dimensional array with object literals
var array2 = [[1,{x:1, y:2}], [2, {x:3, y:4}]];

// the 3rd element is undefined
var colors = ["Blue", "Red", undefined];

// no value in the 1st element, it is undefined
var hobbies = [,"Art"];

Accessing array elements

The elements of an array have an index no that is used to access or change their values.

For example:

var ar = ['apple', 'orange', 'guava', 'banana', 'black berry'];
// access first element in array
alert( ar[0] ); // apple

//access third element in array
console.log( ar[2] ); // guava

//access full array
alert(cars); // apple, orange, guava, banana, blackberry

//You can change the value of an existing array
ar[4] = 'raspberry'; // change ar[4] from blackberry to raspberry

// You can also create a new array element using square brackets and an index
ar[5] = 'fig'; // add new element

Length Property of Arrays

The length property of an array returns the length of an array (the number of array elements).

For example:

<body>
     <h1>JavaScript Arrays</h1>
     <p>The length property returns the length of an array.</p>
     <p id="demo"></p>
  <script>
     var fruits = ["Banana", "Orange", "Apple", "Mango"];
     document.getElementById("demo").innerHTML = fruits.length;     
     // length of fruit is 4
  </script>
</body>

Looping Array Elements

For example:

<html>
<body>
     <p>The best way to loop through an array is using a standard for loop:</p>
     <p id="demo"></p>
<script =”text/javascript”>
   var fruits, text, fLen, i;
   fruits = ["apple", "mango", "guava", "blackberry"];
   fLen = fruits.length;
   text = "<ul>";
   for (i = 0; i < fLen; i++) {
       text += "<li>" + fruits[i] + "</li>";
   }
   text += "</ul>";
   document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Iteration over array

Iteration means repetition (Repetition of a sequence of instructions). When we traverse an array, we can access each of its elements in turn and perform some action.

This will be done by using loops (for loop , while loop)

Example 1

var cars = [];
cars[1] = "suzuki";
cars[3] = "ford";
cars["six"] = "Honda";
for (var i = 0; i < cars.length; i++) {
    alert(cars[i]);     // => undefined, Ford, undefined, BMW
}
// To skip missing and undefined elements, add this condition.
for (var i = 0; i < cars.length; i++) {
    if (cars[i] === undefined)      // skip undefined elements
        continue;
    
    alert(cars[i]);          //  => Ford, suzuki
}

Example 2 : Modifies the array by multiplying each of its values times 2

var ar = [5,6,7,8,9,];
for (var i=0, len = ar.length; i<len; i++) {
    ar[i] *= 2; // multiply value times 2
}
console.log( ar ); // [10, 12, 14, 16, 18]

Eample 3 : check each array element before act on it to see whether it is undefined or null, or whether it is the correct type, etc.

Here we check the whether value is numeric

var ar = ['zero', 1, 'two', 3, 'four', 5, null, 'six'];
var sum = 0; // to hold sum of numeric array values
for (var i=0, len=ar.length; i<len; i++) {
    // check to be sure current array value is numeric
    if ( typeof ar[i] === 'number' ) {
        sum += ar[i]; // if so, add its value to sum
    }
}
console.log( sum ); // 9

Multidimensional Arrays in JavaScript

JavaScript does not have a special syntax for creating multidimensional arrays or in other words JS does not natively support arrays of more than one dimension; we have to create them ourselves.

Example

var twoDim = [];
for (var row = 0; row < 5; row++) {
    var oneDim = [];
    for (var col = 0; col < 5; col++) {
        oneDim[col] = (row === col) ? 1 : 0;  // 0 or 1 (diag)
    }
    twoDim[row] = oneDim;
}
alert(twoDim[4][2]);              
// => 0  // access elements in a 2-dimensional array
alert(twoDim[3][3]);              
// => 1 // access elements in 2 dimensional array

Example

Access Elements of a Multidimensional Array

<script type="text/javascript">
    var ar = [
       ['apple', 'orange', 'pear'],
       ['carrots', 'beans', 'peas'],
       ['cookies', 'cake', 'muffins', 'pie']
    ];
    alert( ar[2][1] ); // cake
</script>

First square bracket in alert() references the desired element in the outer array.

The second square bracket references the desired element in the inner array.

So ar[2][1] references the second element in the third sub-array.

Adding and Removing Elements in Multidimensional Arrays

We can use square bracket notation to add elements to the inner arrays.

For example:

// Here we adding a new element at the end of the first sub-array

var ar = [
    ['apple', 'orange', 'pear'],
    ['carrots', 'beans', 'peas'],
    ['cookies', 'cake', 'muffins', 'pie']
];
ar[0][3] = 'banana';
console.log( ar[0] ); // ["apple", "orange", "pear", "banana"]

//Here we use the push method to add two new elements to the second sub-array
ar[1].push('kale', 'broccoli');
console.log( ar[1] ); // ["carrots", "beans", "peas", "kale", "broccoli"]

//Here we using the push method to add a new array element to the outer array
ar.push( ['fried chicken', 'pot roast', 'rib-eye steak'] );

//we can also use array methods to remove elements from sub-arrays (with pop())

ar[2].pop(); // remove last element from 3rd sub-array
alert( ar[2] ); // cookies,cake,muffins

Looping through Multidimensional Arrays

When we want to iterate or repeating over the elements of a multidimensional array, use nested for loops.

For example:

var ar = [
    ['apple', 'orange', 'pear'],
    ['carrots', 'beans', 'peas'],
    ['cookies', 'cake', 'muffins', 'pie']
];
// outer loop applies to outer array
for (var i=0, len=ar.length; i<len; i++) {
    // inner loop applies to sub-arrays
    for (var j=0, len2=ar[i].length; j<len2; j++) {
        // accesses each element of each sub-array in turn
        console.log( ar[i][j] );
    } // apple, orange, pear, carrots, beans, peas, cookies, cake, muffins, pie.
}

Deleting array elements with delete command

To remove an element from an array you can use the delete operator.
Deleting an element does not affect the length property means delete the value not index number

For example

var days = ["Friday", "Saturday", "Sunday", "Monday"];
delete days[2]; // => delete the element at index 2
alert(days[2]); // => undefined
alert(days.length);

Associative Arrays

Arrays with named indexes are called associative arrays. But JS not support arrays with named indexes. In JavaScript arrays always used numbered indexes.

<html>
<body>
<p id="demo"></p>
<script>
     var person = [];
     person[0] = "John";
     person[1] = "Doe";
     person[2] = 46;
     var x = person.length; // return 3
     var y = person[0]; // return "John"    
     document.getElementById("demo").innerHTML =person[0] + " " + person.length;
</script>
</body>
</html>

Note: If use named index, JS will redefine the array to a standard object and all properties and method of array gives incorrect results.

Difference Between Arrays and Objects

Arrays

  • Arrays use numbered indexes
  • Use arrays when you want the element names to be numbers

Objects

  • objects use named indexes
  • Use objects when you want the element names to be strings (text).

How to Add Elements to an Array

There are many ways to add elements to existing arrays in JS. We can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice.

For example:

Add a new element to an array simply by specifying a new index and assigning a value

var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar

Add Elements to the End of an Array

Use the array’s length property to add an element to the end of the array

ar[ar.length] = 'five';
console.log( ar ); // ["one", "two", "three", "four", "five"]

Array push( ) Method

It allows you to add one or more elements to the end of an array.
It modifies the array and returns the new length of the array

For example:

var ar = ['one', 'two', 'three'];
ar.push('four');
console.log( ar ); // ["one", "two", "three", "four"]

Use the push method to add more than one new element to an array at a time

ar.push('five', 'six'); // add 2 more elements to ar
console.log( ar ); // ["one", "two", "three", "four", "five", "six"]

Array concat( ) Method

The concat() method is used to join two or more arrays.

It is also adds elements to an array, it does not change the existing array, but instead returns a new array .
It containing the values of the joined arrays.

For example:

<script type="text/javascript">
    var alpha = ["x", "y", "z"];
    var numeric = [4, 5, 6];
    var alphaNumeric = alpha.concat(numeric);
    document.write("alphaNumeric : " + alphaNumeric );  
    // alphaNumeric : x,y,z,4,5,6
</script>
<script type="text/javascript">
     var india = ["Ria", "Neha"];
     var uk = ["Emil", "Tobias", "Lina"];
     var usa = ["Robin"];
     var children = india.concat(uk,usa);
     document.write(children);  
</script>

Example of adding elements to array

<script type="text/javascript">
     var ar = ['four', 'five', 'six'];
     var ar2 = ar.concat('seven');
     console.log( ar2 ); // ["four", "five", "six", "seven"]
     //The concat method will accept multiple arguments:
     var ar3 = ar.concat('seven', 'eight', 'nine');
     console.log( ar3 ); //  ["four", "five", "six", "seven", "eight", "nine"]
     // If an argument is itself an array, its elements will be added rather than the array itself:
     var ar4 = ar.concat( ['one', 'two', 'three'] );
     console.log( ar4 ); //  ["four", "five", "six", "one", "two", "three"]
     // This only applies to the first level however and not to an array contained in an array:
     var ar5 = ar.concat( [4, 5, [6, 7, 8] ] );
     console.log( ar5 ); // [four", "five", "six", 4, 5, [6, 7, 8]]
     // Notice that here the elements of outer array added individually while the sub-array is added as an array  
</script>

Add Elements to the Beginning of an Array – unshift( ) Method

unshift method is used to add elements to the beginning of an array It accepts multiple arguments, adjusts the indexes of existing elements, and returns the new length of the array. (changes the length of an array) The unshift method modifies the array on which it is invoked.

For example: First we invoke unshift passing a single argument, then multiple arguments, displaying the results using console.log:

<script type="text/javascript">
     var ar = ['one', 'two', 'three'];
     // add single element
     ar.unshift('zero');
     console.log( ar ); // ["zero", "one", "two", "three"]
     // add multiple elements
     ar.unshift(0, 1, 2, 3);
     console.log( ar ); // [0, 1, 2, 3, "zero", "one", "two", "three"]
</script>

Insert Elements in the Middle of an Array – splice( ) Method

Splice method can be used for adding and/or removing elements from an array.

The first argument specifies the location at which to begin adding or removing elements.

The second argument specifies the number of elements to delete, if any.

When using splice to add elements to an array, the second argument would be zero.

For example:

<script type="text/javascript">
     var ar = [1, 2, 3, 4, 5, 6]; // arguments: start position, number of elements to delete, elements to add   
     ar.splice(3, 0, 'a', 'b', 'c'); console.log( ar ); // [1, 2, 3, "a", "b", "c", 4, 5, 6]
</script>

This method returns an empty array when no elements are removed; otherwise it returns an array containing the removed elements.

How to Remove Elements from an Array

There are many ways to remove elements to existing arrays in JavaScript. We can remove elements from the end of an array using pop, from the beginning using shift, or from the middle using splice.

We can also remove elements from the end of an arrya by setting the length property to value less than the current value.
Any element whose length is greater or equal to the new length will be removed.

For example:

<script type="text/javascript">
     var ar = [1, 2, 3, 4, 5, 6];
     ar.length = 4; // set length to remove elements
     console.log( ar ); // [1, 2, 3, 4]
</script >

Removing array elements using the delete operator

<script type="text/javascript">
     var ar = [1, 2, 3, 4, 5, 6];
     delete ar[4]; // delete element with index 4
     console.log( ar ); // [1, 2, 3, 4, undefined, 6]
     alert( ar ); // 1,2,3,4,,6
</script>

Note: delete operator does not affect the length property means delete the value not index number

Remove Elements from End of Array – pop() Method

The pop method removes the last element of the array, return that element and updates the length property.

It modifies the array on which it is called.

For example:

<script type="text/javascript">
     var ar = [1, 2, 3, 4, 5, 6];
     ar.pop(); // returns 6
     console.log( ar ); // [1, 2, 3, 4, 5]
</script>

Remove Elements from Beginning of Array – shift() Method

The shift method removes the first element of the array.

It returns the element that has been removed, updates the indexes of remaining elements, and updates the length property.
It modifies the array on which it is called or invoked.

For example:

<script type="text/javascript">
     var ar = ['zero', 'one', 'two', 'three']
     ar.shift(); // returns "zero"
     console.log( ar ); // ["one", "two", "three"]
</script>

Remove Elements from Middle of Array – splice( ) Method

splice method can be used to add or remove elements from an array.

For example:

Here we use the splice method to remove two elements starting from position three:

<script type="text/javascript">
     var ar = [1, 2, 3, 'a', 'b', 'c'];
     // arguments: start position, number of elements to delete
     console.log( ar.splice(3, 2) ); // ["a", "b"]
     console.log( ar ); // [1, 2, 3, "c"]
</script>

View Full Presentation on slideshare:

JavaScript Basics

JavaScript basics from ADMEC Multimedia Institute

Related Posts

Leave a Reply

Call Now