Array in JavaScript

 

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.

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.

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.

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.

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.

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.

Now let us try this sort function on an integer array.

So it works perfectly find with single digit numbers. Now let’s try sorting with a combination of single and double digit numbers.

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.

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.

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.

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.

 

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.

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.

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.

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.

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.

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.

We can insert an element at any index in the array. We can use the splice method to do that.

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.

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.

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.

  • Abbey

    Nice post!!