An array is a collection of objects and these objects may be of different types. The difference between both these types of initialization is that JavaScript engine interprets the literals every time the array is accessed.
Initialization
We can also initialize the array to a specific size. We could also assign values particular elements of the array and when we do this the other elements will be undefined. You can see the same in the sample below where we have used for loop to show the elements of the array.
The elements of an array can be assessed directly by the 0 based index. We can use this 0 based index to get or set the value at a particular index.
function arrayDeclaration() { var arrayObj = new Array("Item 1", 2, true); var arrayObjWLiterals = ["Item 1", 2, false]; var arrayWithSize10 = new Array(10); // initializes array with size 10 var arrayWithUndefinedElements = ["Item 1", , "Item 3", , "Item 5"]; console.log(arrayObj); // ["Item 1", 2, true] console.log(arrayObjWLiterals); // ["Item 1", 2, false] console.log(arrayWithSize10); // [ ] for (var i = 0; i < 5; i++) { console.log("Element number " + (i+1) + " in array is " + arrayWithUndefinedElements[i]); //Element number 1 in array is Item 1 //Element number 2 in array is undefined //Element number 3 in array is Item 3 //Element number 4 in array is undefined //Element number 5 in array is Item 5 } }
When we pass an array in a function then it is a passed as a reference. This means if we change the values in the function then the value of the actual array are also modified. So we have modified the value of the 1st element of the array using array index of 0.
function passArrayInFunc() { var arrayObj = ["Initial Value 1", "Initial Value 2"]; console.log("Array value before passing to function --- " + arrayObj); // Initial Value 1,Initial Value 2 modifyArrayFirstElement(arrayObj); console.log("Array value after passing to function --- " + arrayObj); // Modified Value 1,Initial Value 2 } function modifyArrayFirstElement(arrayObj) { arrayObj[0] = "Modified Value 1"; }
Multidimensional
Multidimensional arrays have array as the elements of an array. In the previous section we saw we can access the element of an array by doing something like arrayObj[1] and this would return the element present at this index however if we do the same for a multidimensional array we will get back an array instead of an element.
var multidimArray = new Array(3); multidimArray[0] = ["Item 0.1", "Item 0.2", "Item 0.3"]; multidimArray[1] = ["Item 1.1", "Item 1.2", "Item 1.3"]; multidimArray[2] = ["Item 2.1", "Item 2.2", "Item 2.3"]; console.log(multidimArray[0]); // ["Item 0.1", "Item 0.2", "Item 0.3"] console.log(multidimArray[1]); // ["Item 1.1", "Item 1.2", "Item 1.3"] console.log(multidimArray[2]); // ["Item 2.1", "Item 2.2", "Item 2.3"] console.log(multidimArray[0][0]); // Item 0.1 console.log(multidimArray[0][1]); // Item 0.2 console.log(multidimArray[0][2]); // Item 0.3
We can use the concat method available on the multidimensional array to put all the arrays in the multidimensional array into a single array. This method takes one or more arrays and appends its elements to the new array.
var arrayObj = multidimArray[0].concat(multidimArray[1], multidimArray[2]); console.log("Single dimensional array from multidimensional array -- " + arrayObj);
Array to string
We can convert an array into a string by simply using the join function on the array. We could simply pass nothing and comma (,) will become the delimiter for the array items or we can pass a parameter to the string function and that will act as a delimiter for each item of the string.
function arrayToString() { var arrayObj = new Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5"); console.log("array join with no parameters - " + arrayObj.join()); // Item 1,Item 2,Item 3,Item 4,Item 5 console.log("array join with '||' as parameter - " + arrayObj.join("||")); // Item 1||Item 2||Item 3||Item 4||Item 5 }
It does not matter what types of objects does the array contains when we call the join methods it converts all the elements into its string equivalents and concatenates all the items of the array.
Sort and reverse sort an array
To sort an array of strings simply use sort method available for the array. We can see in the code below that we have sorted the list of months alphabetically.
function sortstringArray() { var unsortedStringArray = new Array("jan", "feb", "mar", "apr", "may", "june"); console.log("sorted array --- " + unsortedStringArray.sort()); // apr,feb,jan,june,mar,may }
Now let us try this sort function on an integer array.
function sortIntegerArray() { var unsortedIntegerArray = new Array(5, 8, 9, 2, 6, 1, 0, 5, 6, 8, 7, 4); console.log(unsortedIntegerArray.sort()); // [0, 1, 2, 4, 5, 5, 6, 6, 7, 8, 8, 9] }
So it works perfectly find with single digit numbers. Now let’s try sorting with a combination of single and double digit numbers.
unsortedIntegerArray = new Array(5, 23, 13, 9, 8, 59); console.log(unsortedIntegerArray.sort()); // [13, 23, 5, 59, 8, 9]
We get an improperly sorted array. The reason is that sort does not compare numbers but it compares the elements of the array lexically. So to fix this we need to implement our custom compare function which will return the difference of two numbers which we can use in sorting.
console.log(unsortedIntegerArray.sort(compare)); // [5, 8, 9, 13, 23, 59] function compare(a, b) { return a - b; }
Now we get a properly sorted array because for each sort we are using the return value form compare method which is either +ve, -ve or 0. This same function will also work if we have numbers in form of strings. The reason is that the sort method is intelligent enough to convert these strings into numbers automatically and convert them back to string as well.
unsortedIntegerArray = new Array("5", "23", "13", "9", "8", "59"); console.log(unsortedIntegerArray.sort(compare)); // ["5", "8", "9", "13", "23", "59"]
We can achieve a reverse sort array by simply sorting the array and then reversing it as the sort function sorts the elements in the ascending order.
function reverseSortArray() { var unsortedStringArray = new Array("jan", "feb", "mar", "apr", "may", "june", "july", "aug", "sep", "oct", "nov", "dec"); console.log("reverse sorted array --- " + unsortedStringArray.sort().reverse()); // sep,oct,nov,may,mar,june,july,jan,feb,dec,aug,apr }
Array as a Stack and Queue
A stack is an object which adds the items in the linear order and when we retrieve the object we can access only the object that was added at the last and then the object that was added before that.
We can use the array object as a stack. We can use the push method of the array to add elements to the array and when we want to access the last added object we can use the pop method available in the array object.
function arrayAsStack() { var arrayStack = new Array(); arrayStack.push("Item 1"); arrayStack.push("Item 2"); arrayStack.push("Item 3"); arrayStack.push("Item 4"); // This is equivalent to the code above //arrayStack = new Array("Item 1", "Item 2","Item 3","Item 4" ); console.log(arrayStack.pop()); // Item 4 console.log(arrayStack.pop()); // Item 3 console.log(arrayStack.pop()); // Item 2 console.log(arrayStack.pop()); // Item 1 console.log(arrayStack.pop()); // undefined }
A queue is a structure that allows us to enter the items into the queue in a linear way and access the item in the same order as they were added to the queue.
We can have the same behavior by using an array. We can use the push method of the array to add elements to the array and when we want to access the item in the same order they were added we can use the shift method available in the array object.
function arrayAsQueue() { var arrayQueue = new Array(); arrayQueue.push("Item 1"); arrayQueue.push("Item 2"); arrayQueue.push("Item 3"); arrayQueue.push("Item 4"); console.log(arrayQueue.shift()); // Item 1 console.log(arrayQueue.shift()); // Item 2 console.log(arrayQueue.shift()); // Item 3 console.log(arrayQueue.shift()); // Item 4 console.log(arrayQueue.shift()); // undefined }
Create an array from another array
We can create an array from another array by using the slice method available in the array. The slice method accepts two parameters: the start index of the array being sliced and the end index of the array being sliced.
function arraySlicing() { var firstArray = new Array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5"); var secondArray = firstArray.slice(2, 5); console.log(secondArray); // ["Item 3", "Item 4", "Item 5"] }
Now let us check whether the values that we copied into the array were copied as values or as references. We could check it by modifying the value of the array items and see if the changes were reflected in the array.
secondArray[2] = "modified item 5"; console.log(firstArray); // ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"] console.log(secondArray); // ["Item 3", "Item 4", "modified item 5"]
We saw that slice copied the items into the list by copying the values. The reason was because we were copying a primitive type. Now let us create an array which has objects instead of values.
function objectArraySlicing() { var objectArray = new Array(3); objectArray[0] = ["Item01", "Item02", "Item03"]; objectArray[1] = ["Item11", "Item12", "Item13"]; objectArray[2] = ["Item21", "Item22", "Item23"]; var newObjectArray = objectArray.slice(1, 3); console.log(newObjectArray.toString()); // Item11,Item12,Item13,Item21,Item22,Item23 newObjectArray[1][2] = "Modified Item 23"; console.log(objectArray.toString()); // Item01,Item02,Item03,Item11,Item12,Item13,Item21,Item22,Modified Item 23 console.log(newObjectArray.toString()); // Item11,Item12,Item13,Item21,Item22,Modified Item 23 }
So we see that when we slice the array with objects as items we see that the items are copied by references and when we change the value in any of the arrays then the value is changed in both of them.
Search in array
The array object provides us with two methods to search for items in an array. These two methods are indexOf and lastIndexOf. If the item has only one occurrence then both the methods will return the same index of the element and if there are multiple occurrences of the element then the indexOf will return the index of the first occurrence of the element and lastIndexOf will return the index of the last occurrence of the element.
function searchInArray() { var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"]; console.log(arrayToSearch.indexOf("june")); // 3 console.log(arrayToSearch.lastIndexOf("june")); // 7 } //In both of these methods we can optionally specify the starting index of the search and will start searching for the element from that index. console.log(arrayToSearch.indexOf("june", 4)); // 7 console.log(arrayToSearch.lastIndexOf("june", 4)); // 3
Now we specified the starting index in both our methods a 4 and we see that indexOf return 7 as the first occurrence of june which seems correct. But the lastIndexOf returns 3 which seem strange. Its correct because we said that the starting index of search is 4 and that’s where the search starts from but interestingly the lastIndexOf searches the whole array and then tells the last index and when we specified the start point of search as 4 we made the last index of array as 3 instead of 7.
Insert, replace and remove elements from array
The splice method is used to remove the elements form the array. So in the code below we have passed 3 and this will remove all the elements from the array but first three.
In the next block of code we have passed -3 and this will remove the last 3 elements from the array.
function removeFromArray() { var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"]; console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june arrayToSearch.splice(3); console.log("Array after -- " + arrayToSearch); // jan,mar,may var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"]; console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june arrayToSearch.splice(-3); console.log("Array after -- " + arrayToSearch); // jan,mar,may }
We can insert an element at any index in the array. We can use the splice method to do that.
function insertInArray() { var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"]; console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june arrayToSearch.splice(3, 0, "july"); console.log("Array after -- " + arrayToSearch); // jan,mar,may,july,june,dec,apr,may,june }
Here we have passed 3 parameters to the splice method:
- Index: We have passed 3 as the index where we insert the new element.
- Element count to remove: We have passed 0 as number of elements we want to replace.
- Element to add: We have passed “july” as the element we want to insert.
We can use a combination of splice and indexOf methods to remove and replace elements within an array.
function replaceInArray() { var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"]; console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june arrayToSearch.splice(arrayToSearch.indexOf("june"), 1, "july"); console.log("Array after -- " + arrayToSearch); // jan,mar,may,july,dec,apr,may,june }
We see here that we have passed 3 parameters to the splice method.
- Index: We have passed the index by using the indexof method. This index is the place where we want to insert the new element.
- Element count to remove: We have passed 1 as number of elements because I want to replace june.
- Element to add: We have passed “july” as the element we want to insert.
Till now we have just passed one element that we want to add to the array. We can pass a list of elements we want to add to the array.
function addMultipleElements() { var arrayToSearch = ["jan", "mar", "may", "june", "dec", "apr", "may", "june"]; console.log("Array before -- " + arrayToSearch); // jan,mar,may,june,dec,apr,may,june arrayToSearch.splice(1, 7, "feb", "mar", "apr", "may", "june", "july", "aug"); console.log("Array after -- " + arrayToSearch); // jan,feb,mar,apr,may,june,july,aug }
The code for this post can be found here.
Any questions, comments or feedback is really appreciated.