Array Prototype Methods

Contact Us or call 1-877-932-8228
Array Prototype Methods

Array Prototype Methods

The following methods are applied to instances of Array.

Array.prototype.fill()

The fill method mutates (changes) the array instance to which it is applied, filling all elements (or some portion of the elements, as dictated by the start and end parameters) with the specified value parameter:

Array.prototype.fill(value, start?, end?)

The start value is the index from which to start filling; the end value is the index up to which to (but not including) to end filling. Note that indexing here is 0-based (the first element has index 0), and that the optional start? and end? parameters default to 0 and the length of the array.

A negative start value is interpreted as length + start. Similarly, a negative end value is interpreted as length + end.

The following example illustrates the use of fill:

Code Sample:

AdvancedArrays/Demos/fill.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.fill</title>
</head>
<body>
	<h1>Array.prototype.fill</h1>
	<script>
		document.write([1, 2, 3, 4].fill(17));
		document.write('<hr>');
		document.write([1, 2, 3, 4].fill(17, 2));
		document.write('<hr>');
		document.write([1, 2, 3, 4].fill(17, 0, 2));
		document.write('<hr>');
		var fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
		document.write(fruits.fill('zucchini', -3, -1));

	</script>
</body>
</html>

Code Explanation

On line 10, we fill a four-element array of integers with the value 17.

On line 12, we fill the same array with the value 17, starting at index 2 - thus filling the latter two (indices 2 and 3) elements.

On line 14, we will the same arra with the value 17, starting at index 0 and ending before index 2 - thus filling the first two (indices 0 and 1) elements.

In the last example, on line 16, we fill a five-element array of strings with the value zucchini using negative start and end parameters: -3 for start means "start filling at the third element from the end" and -1 for end means "stop filling before the last element".

Array.prototype.filter()

The filter method returns a new array from the array to which it is applied (without changing the original array) where each element passes a test, supplied to the method as a callback function:

Array.prototype.filter(callbackFunction, thisArgument?)

The function passed as callbackFunction should return true or false as it is applied to each element. Optionally, we can supply a value for callbackFunction to use as this.

Code Sample:

AdvancedArrays/Demos/filter.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.filter</title>
</head>
<body>
	<h1>Array.prototype.filter</h1>
	<script>
		var arrNums = [10, -3, 39, 25, 88];
		function greaterThan17(val) {
			return val > 17;
		}
		var arrBiggerThan = arrNums.filter(greaterThan17);
		document.write(arrBiggerThan);
		
		
		document.write('<hr>');

		
		var arrDates = [];
		arrDates.push(new Date(2016, 04, 01));
		arrDates.push(new Date(2015, 01, 19));
		arrDates.push(new Date(1977, 11, 13));
		arrDates.push(new Date(1999, 01, 01));
		function laterThan(d) {
			var dateTest = new Date(1990, 01, 01);
			return d > dateTest;
		}
		var arrDatesLaterThan = arrDates.filter(laterThan);
		document.write(arrDatesLaterThan);


		document.write('<hr>');


		var arrPossibleSquares = [1, 2, 9, 16, 24, 36, 41];
		function isPerfectSquare(n) {
			return n > 0 && Math.sqrt(n) % 1 === 0;
		}
		var arrPerfectSquares = arrPossibleSquares.filter(isPerfectSquare);
		document.write(arrPerfectSquares);


		document.write('<hr>');


		var arr = [10, 21, 4, 88, 4, 10, 10, 14, 37, 21];
		function isUnique(val) {
			var count = 0;
			for (var i in arr) {
				if (val == arr[i]) {
					count++;
					if (count > 1) {
						return false;
					}
				}
			}
			return true;
		}
		var uniqueElements = arr.filter(isUnique, arr);
		document.write(uniqueElements);

	</script>
</body>
</html>

Code Explanation

Our filter.html file shows four examples of using filter. The first example uses a callback function, greaterThan17, to return true for elements greater than 17. The expression arrBiggerThan = arrNums.filter(greaterThan17) creates a new array arrBiggerThan which contains all of the elements from arrNums which are greater than 17.

In our second example we create an array (arrDates) of Date objects, then use filter to create a new array (arrDatesLaterThan) of only those dates from arrDates which are later than 1/1/1990.

The third example tests each element of the array arrPossibleSquares to see if the element is a perfect square, populating array arrPerfectSquares with those element for which callback function isPerfectSquare returns true.

In the last example we demonstrate the use of the optional thisArg parameter. Recall that the value of this in any JavaScript function is, by default, the global window object. By passing the original array (arr) as the thisArg parameter in the call arr.filter(isUnique, arr), we give callback function isUnique a way to access the original array. Function isUnique counts the number of occurrences of its parameter val, returning true if and only if there is exactly one occurrence. Thus our array uniqueElements contains only the elements from arr which occur exactly once.

Array.prototype.find()

The find method returns the first element from the array for which the callback function returns true; if no such element exists, then find returns undefined:

Array.prototype.find(callbackFunction, thisArgument?)

The method takes an optional second parameter to use as this when executing callbackFunction.

In the next set of examples, we demonstrate how to use the find method with an array of objects:

Code Sample:

AdvancedArrays/Demos/find.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.fin</title>
</head>
<body>
	<h1>Array.prototype.find</h1>
	<script>
		var people = [
			{
				fname:'Maria',
				lname:'Martinez',
				id:14637,
				hireDate:new Date(1999,2,4)
			},
			{
				fname:'Jane',
				lname:'Doe',
				id:29384,
				hireDate:new Date(2003,4,13)
			},
			{
				fname:'John',
				lname:'Doe',
				id:39922,
				hireDate:new Date(2004,11,20)
			},
			{
				fname:'Mary',
				lname:'Chan',
				id:83736,
				hireDate:new Date(2014,7,4)
			}
		];

		function hiredAfter2000(person) {
			var jan012000 = new Date(2000,1,1);
			return person.hireDate >= jan012000;
		}

		var firstPersonHiredAfter2000 = people.find(hiredAfter2000);
		document.write('The first person hired after 1/1/2000 is ' + firstPersonHiredAfter2000.fname + ' ' + firstPersonHiredAfter2000.lname);


		document.write('<hr>');
		

		function hasId(person, id) {
			return person.id === id;
		}
		var idToFind = 83736;
		var person = people.find(function(p) {
			return hasId(p, idToFind);
		});
		if (typeof person != 'undefined') {
			document.write(person.fname + " " + person.lname + " has id " + idToFind);
		} else {
			document.write("person not found");
		}

		document.write('<hr>');

		var idToFind2 = 11111;
		var person2 = people.find(function(p) {
			return hasId(p, idToFind2);
		});
		if (typeof person2 != 'undefined') {
			document.write(person2.fname + " " + person2.lname + " has id " + idToFind2);
		} else {
			document.write("person not found");
		}

	</script>
</body>
</html>

Code Explanation

We create an array people where each of the four elements is an object with fields for first name, last name, ID, and date of hire; the array is sorted by hire date, with earlier hires first.

We use the find method with callback function hiredAfter2000 to create firstPersonHiredAfter2000; since the second element of our array is the first element with a hire date later than 1/1/2000, the "Jane Doe" record is the element found and written to the screen.

In the latter two examples we search for the person-object with a specific ID, calling the function hasId in our find method. On line 33 we get the "Mary Chan" element (which has an id of 83736).

On line 45 our find call returns no array element (there is no person with id 11111) and, thus, our test typeof person2 != 'undefined' fails and person not found is written to the screen.

Array.prototype.forEach()

The array method forEach gives us a way to apply a callback function to each element of the array:

Array.prototype.forEach(callbackFunction, thisArgument?)

The method takes an optional second parameter - the value to use as this for the callback function.

The callback function specified by the callbackFunction parameter takes three arguments: the current element, the index of the current element, and the array to which forEach is being applied.

Note that there is no way to break out of a forEach loop other than by throwing a JavaScript exception; use a for loop or similar construct if this behavior is needed.

The following example shows the use of the forEach method:

Code Sample:

AdvancedArrays/Demos/forEach.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.forEach</title>
</head>
<body>
	<h1>Array.prototype.forEach</h1>
	<script>
		var nums = [2, 33, 92, 1, 20, 57, 41, 7];

		function writeInfoAsListItem(value, i, arr) {
			document.write('<li>');
			document.write(value + ' at position ' + i + (i < arr.length/2 ? ' (1st half)' : ' (2nd half)'));
			document.write('</li>');
		}

		document.write('<ul>');
		nums.forEach(writeInfoAsListItem);
		document.write('</ul>');
	</script>
</body>
</html>

Code Explanation

We create an eight-element array of numbers, nums, and call forEach on the array on line 19. Our callback function, writeInfoAsListItem, writes to the screen information about each element, formatted as an HTML list item: the value of the element, the index of the element, and whether the element is in the first or second half of the array.

Array.prototype.indexOf()

The indexOf method returns the first index at which the specified element is found in the array to which it is applied, or -1 is the element is not found:

Array.prototype.indexOf(elementToFind, start?)

We can pass an optional parameter to specify the index at which to start the search; passing a start parameter which is greater than or equal to the length of the array returns -1.

In the following example, we use indexOf to search an array and to build a function which returns the unduplicated elements of an array:

Code Sample:

AdvancedArrays/Demos/indexOf.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.indexOf</title>
</head>
<body>
	<h1>Array.prototype.indexOf</h1>
	<script>
		var nums = [2, 32, 92, 1, 2, 20, 57, 32, 2, 41, 7];

		document.write(nums.indexOf(32)); // returns 1
		document.write('<hr>');
		document.write(nums.indexOf(92, 5)); // returns -1
		document.write('<hr>');
		document.write(nums.indexOf(547)); // returns -1

		document.write('<hr>');

		function unique(arr) {
			var arrayOfUnique = [];

			arr.forEach(function(currentElement) {
				if (arrayOfUnique.indexOf(currentElement) == -1) {
					arrayOfUnique.push(currentElement);
				}
			});
			
			return arrayOfUnique;
		}

		document.write('Original array: ' + nums);
		document.write('<br>Unique elements: ' + unique(nums));

		

	</script>
</body>
</html>

Code Explanation

nums is an array of integers; note that a few of the elements (2 and 32) are duplicated.

Our call to nums.indexOf(32) on line 12 returns 1, since the first occurrence of 32 in the array comes at index 1.

The call nums.indexOf(92, 5) returns -1 since the value 92 is not found in the array if we start looking from index 5.

The call nums.indexOf(547) returns -1 since the value 547 is not present in the array.

Our function unique returns an array of unduplicated elements: we loop over the array, adding each current element to a new (initially empty) array arrayOfUnique if the current element has not (arrayOfUnqiue.indexOf(currentElement) == -1) already been added to it.

Array.prototype.keys()

The array method keys returns a new Array Iterator with the keys from each index of the array to which it was applied. It does not change the array on which it is called:

Array.prototype.keys()

Note that the keys method does not ignore "holes" in the array, as in the array ['one', , 'three']. The following example shows the use of keys:

Code Sample:

AdvancedArrays/Demos/keys.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.keys</title>
</head>
<body>
	<h1>Array.prototype.keys</h1>
	<script>
		var nums = [10, 20, 30, 40];
		iter = nums.keys();
		while (true) {
			current = iter.next();
			if (current.done) {
				break;
			}
			document.write(current.value + '<br>');
		}

		document.write('<hr>');

		var nums2 = [1, , 3];
		iter = nums2.keys();
		while (true) {
			current = iter.next();
			if (current.done) {
				break;
			}
			document.write(current.value + '<br>');
		}
	</script>
</body>
</html>

Code Explanation

In the first example we get the keys from a four-element array as an iterator and use the next() method and done property to loop over the iterator object, writing 0, 1, 2, and 3 (the indices of the four elements) to the screen.

The second example shows that the "missing" second element of array nums2 still results in the values 0, 1, and 2 being written to the screen.

Array.prototype.map()

The map method returns a new array from the application of its callback-function parameter to each element of the original array:

Array.prototype.map(callbackFunction, thisArgument?)

Optionally, we can supply a value for the callback function to use as this.

The callback function is excuted on each element of the array in order and takes three arguments: the current element, the current index, and the original array to which map is being applied.

In the following example, we use the map method to round an array of numbers and to produce an array of full names from an array of objects:

Code Sample:

AdvancedArrays/Demos/map.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.map</title>
</head>
<body>
	<h1>Array.prototype.map</h1>
	<script>
		var nums = [1.21, 2.6, 3.3, 4.76];
		var roundedNums = nums.map(Math.round);
		document.write(roundedNums);

		document.write('<hr>');

		var people = [
			{fname:'Marla', lname:'Jayson'},
			{fname:'Jack', lname:'Patel'},
			{fname:'Eric', lname:'Song'},
			{fname:'James', lname:'Doe'}
		];
		function getFullName(person) {
			return person.fname + ' ' + person.lname;
		}
		var peopleFullNames = people.map(getFullName);
		document.write(peopleFullNames);
	</script>
</body>
</html>

Code Explanation

The array nums contains four floating-point values. We create array roundedNums from nums by supplying Math.round as the callback function for map, thus rounding each element of nums to the nearest integer.

The array people contains four objects, each with fields for first name and last name. The callback function getFullName returns the first and last name concatenated with a space; people.map(getFullName) thus produces an array with the full name of each element of the original people array.

Array.prototype.reduce()

The reduce method applies a callback function once for each value of the array, offering a means to return a single, calculated value - the sum of all elements, for example - from the array:

Array.prototype.reduce(callbackFunction, initialValue?)

The callback function executed by reduce takes four arguments:

  • previousVal: The value previously returned by the last invokation of the callback function, or the initalValue parameter, if present.
  • currentVal: The current element being processed.
  • currentInd: The index of the current element being processed.
  • arr: The array upon which reduce was called.

If you apply reduce to an array and do not supply an initialValue parameter, then previousVal will be equal to the first value of the array and currentVal will be equal to the second value of the array.

Let's look at a few examples to better explain the use of reduce:

Code Sample:

AdvancedArrays/Demos/reduce.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Array.prototype.reduce</title>
</head>
<body>
	<h1>Array.prototype.reduce</h1>
	<script>
		var nums = [6, 2, 4, 7, 9, 11];
		var total = nums.reduce( (a, b) => a + b );
		document.write(total);

		document.write('<hr>');

		function isPrime(num) {
			if (num < 2) {
				return false;
			}
			var sqroot = Math.sqrt(num);
			for (var i=2; i<=sqroot; i++) {
				if (num % i == 0) {
					return false;
				}
			}
			return true;
		}

		function countPrimes(total, num) {
			if (isPrime(num)) {
				return total + 1;
			}
			return total;
		}

		var numPrimes = nums.reduce(countPrimes, 0);
		document.write(numPrimes);

		document.write('<hr>');

		var average = nums.map( function(value, i, arr) {
			return value / arr.length;
		}).reduce( (a, b) => a + b );

		document.write(average);
	</script>
</body>
</html>

Code Explanation

We demonstrate three uses of reduce, all applied to our six-element array of integers nums.

In the first example on line 11, we find the sum of the elements of the array using a callback function defined as an arrow function (a,b) => a+b. Because we do not supply the optional initialValue parameter in our call to reduce, the first execution of the arrow function takes the first element (6) as previousVal and the second element (2) as currentVal, returning their sum, the value 8. Remember that the arrow function - the callback function supplied to reduce - is executed once per element; the second time it is executed it receives the value returned from the last call (8) as previousVal and the third element (4) as currentVal, returning their sum as 12. This process of generating a running sum continues until all elements have been processed and the total sum, or 39, is returned.

The second example invokes callback function countPrimes, with parameters total and num; these are the previousVal and currentVal parameters, respectively. On line 36 we supply 0 for initialValue; for each iteration of the callback function, countPrimes increments the running count of primes if the current element being processed (its parameter num) is indeed prime - that is, if our utility function isPrime returns true for that value.

In our last example, we chain together the map and reduce methods on our array to get the average (mathmatical mean) of the elements in array num. We use the map method to return a new array which is the result of dividing each element in nums by the length of nums; we then use reduce to find the sum of the elements of that array. Since addition is commutative over division (that is, adding the elements and then dividing by the total number of elements is the same as dividing each element by the total number of elements and adding the results), we get the average of the array.

We'll ask you to try out Array methods in the next exercise:

Next