Arrays in JavaScript

Posted on - Last Modified on

The basic collection data structure inside JavaScript is the array. Arrays can be very handy when you need to group certain types of data together, like a list of cities, or list of numbers, or even a list of objects.

var usCities = ['Dallas', 'New York', 'Miami', 'Palo Alto'];
var euCities = new Array('Paris', 'London', 'Hamburg', 'Madrid');
var allCities = new Array(usCities.length + euCities.length);

There are three ways to create arrays. The first is to use the array index notation and specify all the elements which you would like to have in the array. The second option is to use the Array constructor and specify the items separated by comma. In the example, I used this initialization method to initialize the euCities variable. The third possibility to create a new array is to use the Array constructor, but you only specify a single parameter of type Number.

If you execute this code:

console.log('Cities in the US: ' + usCities);
console.log('Cities in the EU: ' + euCities);
console.log('Cities around the world are: ' + allCities + ' and the array has a length of: ' + allCities.length);

On the console, the following will appear:

Cities in the US: Dallas,New York,Miami,Palo Alto

Cities in the EU: Paris,London,Hamburg,Madrid

Cities around the world are: ,,,,,,, and the array has a length of: 8

Accessing the elements stored in the array can be done using the index operator []:

console.log(usCities[0]);  // Dallas
console.log(euCities[euCities.length - 1]); //Madrid

The indexing of elements inside an array starts from 0 (as in most of the programming languages) and the last element of an array has the array’s length minus 1 index. Array’s elements can be accessed using for and loops to:

console.log('The cities in the euCities array are:');
for (var i = 0; i < euCities.length; i++) {
  console.log(euCities[i]);
}

console.log('Indexes for US Cities are:');
for (var idx in usCities) {
  console.log(idx + ' for ' + usCities[idx]);
}

The output of the code is the following:

The cities in the euCities array are:
Paris
London
Hamburg
Madrid

Indexes for US Cities are:
0 for Dallas
1 for New York
2 for Miami
3 for Palo Alto

The join() method can be used to build up a string of the elements inside an array. To join() method by default uses the comma(,) as an element separator when creating the new string, but you can specify what separator should be used.

console.log(usCities.join(' =|= '));
console.log(euCities.slice(1,3));
console.log('The index of London in euCities is: ' + euCities.indexOf('London'));

The result of the above code is:

Dallas =|= New York =|= Miami =|= Palo Alto

[ 'London', 'Hamburg' ]

The index of London in euCities is: 1

The slice() method can be used to create a new array containing a slice of the initial array. This receives two parameters, the start index where the slice should start and the end index of the slice. In this example, the start index is 1 and the end index is 3, so the result is London and Hamburg from the euCities array.

There are cases when you want to find an element in an array, so you can access or substitute it with something else. This is when the indexOf() method can be of help. You need to pass the value which you want to look up in the array, and if that value exists, the indexOf() method will return the item’s index.  If the value does not appear in the array, then -1 is returned. So in our example in the euCities array, London is stored on index 1.

The fill() method can be used to initialize the array with the same element:

var myNumbers = [].fill(13, 0, 5);
console.log(myNumbers);
myNumbers = new Array(4).fill(13);
console.log(myNumbers);
myNumbers.push(14);
myNumbers.push(15);
console.log(myNumbers);

The output of the code is:

[]
[ 13, 13, 13, 13 ]
[ 13, 13, 13, 13, 14, 15 ]

The first usage of the fill() method can take three arguments. The first is the value you want to initialize your array with. The second parameter is the start index, where the fill method should start to add the value. The last parameter is the end index, where the filling should end. In the first example, I want to initialize an empty array with the value 13, starting from index 0, and I want to have the items fill the element with index 5.

Although this usage of the fill() method is legitimate, it will not result in what I want, because the fill method changes the current array and does not create a new one. So, for the first usage, I basically say I want to fill an array which has a length of 0 with elements from index 0, and of course, this is not possible.

For the second usage of fill() I use an array which has a length of 4, so the method can do what it was created for and will update my array to have 4 elements, and each element to be 13.

The push() method adds a new item to the end of the array, and as you can guess, the length of the array is also adjusted.

The inverse method of push() is pop() which removes the last element from the array:

myNumbers.pop();
console.log(myNumbers); // [ 13, 13, 13, 13, 14 ]

The reverse() method reverses the elements in the array:

euCities.reverse();
console.log('After reverse() euCities is: ' + euCities);
After reverse() euCities is: Madrid,Hamburg,London,Paris

Another useful method that can be used when working with arrays is the sort() method. The sort() method sorts the elements in the array and uses the characters' Unicode value for comparing, but you may override the sorting algorithm by implementing your own sort function. The function should return -1 for items which are smaller than others, 0 for equal values and 1 for values which are greater.

In this code, I created a random array using Math.random() method. Then I used concat() method of the array, to put the values of two arrays together. After setting up the tmpArray, I applied the default sort method and after that, I applied it again with my own logic.

var tmpArray = [];
for(var i=0; i<10; i++){
  tmpArray.push(Math.floor(Math.random() * 100) + 1);
}

tmpArray.push('Philadelphia');
tmpArray = tmpArray.concat(['Boston', 'Chicago']);
console.log('My tmpArray is: ' + tmpArray);
tmpArray.sort();
console.log('My tmpArray after default sort is: ' + tmpArray);

tmpArray.sort(function(val1, val2){
  if(val1.toString().length < val2.toString().length) {
    return 1;
  }
  else {
    return -1;
  }
  return 0;
});

console.log('My tmpArray after my algorithm sort is: ' + tmpArray);

After execution, the output is:

My tmpArray is: 100,5,77,61,83,59,48,39,14,51,Philadelphia,Boston,Chicago

My tmpArray after default sort is: 100,14,39,48,5,51,59,61,77,83,Boston,Chicago,Philadelphia

My tmpArray after my algorithm sort is: Philadelphia,Chicago,Boston,100,51,14,61,77,83,48,39,59,5

Hopefully, through this article, you learned how Arrays can be used in JavaScript. I covered initialization, how to access elements, the fill(), indexOf(), join(), concat(), slice(), splice(), sort(), reverse() and sort() methods. If you know how to use these methods of an array, you can basically do anything with arrays.

Posted 26 January, 2016

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Next Article

How to Use Psychology in Creating Social Media Campaigns