Lesson 11: JS Arrays

Kerry Powell
Web Development For Beginners
6 min readJul 31, 2017

An array in JavaScript is the same as any other programming language. They are collections of data. In JavaScript they can be a collection of strings, numbers, objects, arrays, and functions. They can also be a mix of data types.

Like any other data structure in JavaScript, they have a set of methods/functions that can be called to get, set, manipulate, transform and delete items in the array or to even merge two arrays.

Defining an Array

There are multiple ways to define an array:

Using a Constructor

Constructors are used to create a new instance of an object. Hence they use the ‘new’ key word.

var arr = new Array(); 

Doing this will create an empty array. You can instantiate the array with a predefined set of data by doing this:

var arr = new Array(1,2,3);

Shorthand

The shorthand method does not require the use of the ‘new’ key word or the Array method to be called. You just define the array using square brackets:

var arr = [];

To pre-populate the array with data:

var arr = [1,2,3];

Adding Items to an Array

To add an item to the end of an array you use the push method:

var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]

To add an item to the front of an array we use unshift

var arr = [1,2,3];
arr.unshift(0);
// arr is now [0,1,2,3]

To add an item at a certain position in the array you would use splice which takes 3 arguments. The first is the index where to start modifying, the second is the number of items to delete (since we are only inserting we will pass 0), and the third is the value to insert. (splice will take as many arguments as you pass in, values after the second argument will be added to the array at the position specified)

var arr = [1,2,4];
arr.splice(2,0,3);
// arr is now [1,2,3,4]

Deleting Items From an Array

To delete an item from the end of an array use the pop method:

var arr = [1,2,3,4];
arr.pop();
// arr is now [1,2,3]

To delete an item from the start of an array use the shift method:

var arr = [0,1,2,3];
arr.shift();
// arr is now [1,2,3]

To delete an item from a certain position in the array use splice

var arr = [1,2,3,3,4];
arr.splice(2,1);
// arr is now [1,2,3,4];

Merging Arrays

To merge an array we use the concat method:

var arr1 = [1,2,3],
arr2 = [4,5,6];
arr = arr1.concat(arr2);
// arr is [1,2,3,4,5,6];

Sorting Arrays

In JavaScript numbers and strings are sorted as expected, in numerical order, and alphabetical order. Watch out for arrays of numerical strings though. If you sorted ['1','2','3','4','5','6','7','8','9','10'] you might expect nothing to happen because they seem to be in order. But because they are strings you would actually get ['1','10','2','3','4','5','6','7','8','9'] We will go over how to overcome this but first we need the simple example:

Simple Sort

var arr = [2,1,3,4,6,5];
arr = arr.sort();
// arr is now [1,2,3,4,5,6]arr = ['b','a','d','c','e'];
arr = arr.sort();
// arr is now ['a','b','c','d','e']

Complex Sort

var arr = ['2','4','6','8','1','3','5','7','9','10']
arr.sort((a,b)=>{
var returnVal = 0;

a = parseInt(a);
b = parseInt(b);

if (a < b) {
returnVal = -1;
}

if (a > b) {
returnVal = 1;
}
return returnVal;
})
console.log(arr);

Sort can take a custom function that will be called for every item in an array. The function will be called with 2 arguments, the current index value and the next index value. To move an item to a lower index you should return -1, for a higher index return 1 and to keep the item in the same position return 0. In the above example we first parse the number strings to integers. Then we compare them against each other and return the appropriate value.

Filtering Arrays

Nothing special to explain here. A filter works how you might guess:

var arr = ['apple','orange','lemon','carrot','potato','celery'];function isFruit(val) {
return ['apple','orange','lemon'].includes(val);
}
arr = arr.filter(isFruit);// arr is now ['apple','orange','lemon']

Note: in the previous example we use an array method includes which at the time of writing is not supported by IE, but it is supported by edge. If you need to support IE you would do something like this:['apple','orange','lemon'].indexOf(val) !== -1;

Utility Methods

There are a couple utility methods of arrays that are very useful:

arr.length() — Gives the total number of items in an array

arr.indexOf(item) — Returns the index, of the the item passed in, within the array. If an item is not found it returns -1

arr.includes(item) — Returns a boolean (true or false) depending on if the passed in item is found in the array. This is not supported in any version of IE, but it is in Edge

arr.some(item => item > 10) — Returns a boolean based on if the given condition returns true for some of the array items. This takes a function, I show it using an arrow function for simplicity

arr.reverse() — Reverses the array items within the array. If an array had 10 items, the item originally at index 0 would be relocated to index 9 and so on.

Reducers

A reducer is used to accumulate values and return them in a smaller array or a singular value. This example is taken from MDN.

var total = [0,1,2,3].reduce(function(accumulatedValue, currentItemValue){
return accumulatedValue + currentItemValue;
}, 0) // 0 is the initial value of the accumulated value.

The reduce method iterates over the array and for every item in the array calls a method that accepts a callback function and the initial value of the accumulator. The callback method is called with 2 parameters, the current accumulated value, and the current item value. Since this example is asking for a total of the items in the array we just add the accumulated value to the item value and return it.

ForEach

The forEach method is a simple way to perform an action for every item in an array. The method does not return anything, or modify the original array. Here is an example of how you might use it:

var arr = [1,2,3,4],
doubled = [];
arr.forEach(val => doubled.push(val*2));// doubled is now [2,4,6,8]

Map

map is a lot like forEach except that it return a new array based on the actions performed on each item:

var arr = [1,2,3,4],
doubled = arr.map(val => val*2);
// doubled is [2,4,6,8]

Iterators

I used the word ‘iterator’ in this article to refer to a way a method does something for every item in an array. There are specific iterators on arrays also. For these iterators a next() method is called every time you are ready for the next value in the array. There are 2 array methods that return iterators:

keys — iterates over all keys in an array or object (not supported by IE)

values — iterates over all values in an array or object (not supported by Chrome, or IE)

Here is an example of how you might use an iterator:

var arr = ['a','b','c'],
iterator = arr.keys(),
str = '';
function consStr(iter) {
var next = iter.next();
if (!next.done) {
str = str + arr[next.value];
consStr(iter);
}
}
consStr(iterator);// str = "abc"

The nice thing about iterators is that you do not have to perform all the actions on an array at once. The next method of the iterator can be called at anytime after the iterator is defined.

There are many methods and ways to work with arrays. For a full documentation go to MDN, there you can see code examples, explanations and browser compatibility for all the array methods. Up next I will cover some odds and ends an cover some things that are useful to know, as well as some things that come up in interview questions.

--

--

Kerry Powell
Web Development For Beginners

Front-End developer working at the Church of Jesus Christ of Latter-day Saints.