Introduction

Arrays are highly useful for storing ordered collections of data, but not until they are blended together with array properties and methods.

In this chapter we shall get an overview of the most fascinating methods available to all array instances and the all-time favourite length property.

Properties

length

The length property holds the number of elements in an array. It works similar to the length property of strings.

Consider the following code:

var subjects = ["Chemistry", "Physics", "Maths"];
console.log(arr.length); // 3

First we create an array subjects and then give it three elements, leading to the length property becoming equal to 3.

Methods

slice()

The slice() method is used to literally slice a given array into a subarray.

It extracts out elements from an array, puts them into a new one and finally returns this newly constructed array.

Shown below is its syntax:

arrayObj.slice([start [, end]])

The argument start specifies the index where to start the slicing. This is inclusive i.e slicing begins right exactly at this index. The default value is 0.

Similarly end specifies the index where to end the slicing. This is exclusive i.e slicing ends exactly before this index. The default value is the length of the given array object.

Let's consider a couple of examples:

var nums = [1, 2, 3, 4, 5];

console.log(nums.slice(0, 0)); // []
console.log(nums.slice(0, 1)); // [1]
console.log(nums.slice(1, 4)); // [2, 3, 4]

In the first statement, calling slice(0, 0) returns an empty array because the slicing begins at 0 and ends before 0 (at -1, which is clearly impossible!).

In the second statement, calling slice(0, 1) returns the array [1] by beginning slicing at index 0 and ending it just before 1 (i.e 0).

In the last statement, calling slice(1, 4) returns the array [2, 3, 4] because slicing this time begins at index 1 and ends just before index 4. This accounts for the indexes 1, 2 and 3 (4 being exclusive).

slice() doesn't alter the original array.
Figure out the return value of nums.slice() for the nums array above.

Keep in mind the default values of both the start and end arguments.

undefined
[]
[1, 2, 3, 4]

concat()

The concat() method concats/joins two or more arrays together and returns the final value.

This method is particularly important, if one wants to merge multiple arrays together into a single array you. Just specify the arrays as arguments to the concat() method and get a single, concatenated version.

As discussed in the previous Arrays Basic Concepts chapter, concat() does not modify the original array!

Below we concatenate two arrays b and c to an array a:

var a = [1, 2],
     b = [1, 4],
     c = [6, "Joined"];

console.log(a.concat(b, c));
[1, 2, 1, 4, 6, "Joined"]

The order in which parameters are placed is the order in which the arrays are joined. Consider the following a.concat(c, b) statement:

console.log(a.concat(c, b));
[1, 2, 6, "Joined", 1, 4]
How to achieve the concatenated array [6, "Joined", 1, 2, 1, 4] using the three arrays a, b and c above?
c.concat(a, b)
c.concat(b, a)
c.concat([a, b])
c.concat([b, a])

reverse()

The reverse() method simply reverses the order of elements in a given array.

Note that, reverse() does actually modify the original array.

var subs = ["Chem", "Physics", "Math"];

subs.reverse();

// the actual array has been modified
console.log(subs);
["Math", "Physics", "Chem"]
If you don't want to mess up with the order of elements in the original array, then make its copy and call the reverse() method on that copy.

filter()

The filter() method is used to filter out elements from an array based on some condition and return a new array.

That condition goes in a function as can be seen below:

arrayObj.filter(filterFunction)
  1. filterFunction(element, index): a function run on each element of arrayObj to decide whether it should be included in the new filtered array. If the function returns true, the element is included, or else it's skipped.
    • element is the current element of arrayObj
    • index is the index of element

Let's suppose we have the following array of numbers, from which we want to extract all those that are greater than 100.

var nums = [60, 105, 100, 86, 166, 30];

The filtering code will go as follows:

var nums = [60, 105, 100, 86, 166, 30];

function greaterThan100(e) {
    return e > 100;
}

var filteredArray = nums.filter(greaterThan100);

console.log(filteredArray);
[105, 166]

The moment filter() is invoked in line 3 along with its argument function here's what happens..

The argument function greaterThan100() is called for each element in nums. As it's called, it's passed in two arguments: the next element in the array and its index. If the function returns true for a given element, that element is included in the array constructed by filter().

In the code above, greaterThan100() has only one parameter e, and not a second one. This is because we just don't need the second parameter!

In the case above, greaterThan100() is first called as greaterThan100(60, 0). This call returns false and so 60 is skipped from the new array.

Moving on, the second call made is greaterThan100(105, 1). Since this call returns true, 105 is included in the new array.

This goes on until the end of nums is reached.

This feature of filtering out element from an array can also be accomplished using loops, but at the cost of longer and more complicated code. The filter() method is no doubt worth it!
After you do functions in JavaScript this code will look much easier!

Create an array evens by filtering out all the even-indexed elements from the following nums array:

var nums = [1, 10, 5, 33, 198, 0, 5, 8];

Your evens array shall be equal to [1, 5, 198, 5] as these elements have even indexes in nums - 0, 2, 4, and 6 respectively.

Think of the second parameter of filterFunction()!

var nums = [1, 10, 5, 33, 198, 0, 5, 8];

var evens = nums.filter(function(e, i) {
    return i % 2 === 0;
});

every()

The method every() runs every element, in an array, against a given condition and returns true only if every element meets it or else false.

For example, if the passing marks are above 50, you can check whether or not you passed all exams whose marks are saved in the array passed below:

var marks = [60, 80, 95, 91, 86];
var passed = marks.every(function(m){ return m > 50; }); // this condition runs for every element.

console.log(passed); // true
// All marks were above 50 therefore you get true
Try this method using 70, in the condition, as your passing marks! You should get false, since not every element meets this condition.

find()

As the name suggests, find() is used to find something within an array. However this job is already performed by the indexOf() method - and so what makes this method so special.

The method find() finds the first element in an array that matches a given condition.

In contrast to giving a fixed value and searching it directly in the array, here we search for the first element only, and that which matches a given condtion.

Consider the code below:

var marks = [60, 80, 95, 91, 86];
var a = marks.find(function(m){ return m > 90; }); // this condition runs for every element until one returns true.

console.log(a); // 91
This method utilises linear search and so you should not use it to find elements in large arrays. See more on searching.

sort()

The sort() method sorts elements in an array in ascending or descending order.

var arr = ["Divide", "Subtract", "Add", "Multiply"];
arr.sort();

console.log(arr); // ["Add", "Divide", "Multiply", "Subtract"]
The sort() method is not as simple as it looks!

push()

To add elements at the end of an array use the push() method.

var marks = [10];
marks.push(20);

console.log(marks); // [10, 20]

pop()

The pop() method removes the last element from an array, and returns it.

This method modifies the original array.

Consider the following code:

var nums = [10, 20];

console.log("Removed:", nums.pop());
console.log(nums);

console.log("Removed:", nums.pop());
console.log(nums);
Removed: 20
[10]
Removed: 10
[]

First when we call nums.pop() the last element 20 is removed from nums and returned. The array nums thereby becomes [10].

Afterwards, calling nums.pop() again removes the last element 10 from nums and returns it. This leaves us with an empty nums array.

unshift()

To add elements at the beginning of an array use the unshift() method.

var marks = [20, 30];
marks.unshift(10);

console.log(marks); // [10, 20, 30]

shift()

To remove an element from the beginning of an array use the shift() method.

var marks = [10, 20];
marks.shift();

console.log(marks); // [20]
The methods pop(), push(), shift() and unshift() all modify the original array!