4.1 Arrays
# JavaScript Array Objects
Array
s in JavaScript are simply numbered lists. A list of names, dates, numbers, or anything really. To create an
Array we can use either the Array constructor function or write an Array literal.
//the Array constructor
let names = new Array('Jon', 'Bran', 'Rickon', 'Rob', 'Sansa', 'Arya');
//an Array literal
let names = ['Jon', 'Bran', 'Rickon', 'Rob', 'Sansa', 'Arya'];
2
3
4
5
Arrays in JS are dynamically built and sized, meaning that you can change the number of elements inside one at any time. You do not have to provide a size limit when you create one.
To determine the number of items in an Array, use the length
property.
names.length; // returns 6
The values in an array do NOT all have to be the same datatype but it is considered to be a good practice.
# Viewing and Editing Arrays
If you want to see the value of a single element in an Array, then we use []
after the variable name with an index
number inside it. Array elements are numbered starting at zero. The first element is number zero and the last element
will be the length of the array less one.
names[0]; // Jon (first element)
names[1]; // Bran (2nd element)
// You can also use a variable as the index number too
let item = 3;
names[item]; // Rob (4th element)
let last = names.length - 1; // 5
names[last]; // Arya
2
3
4
5
6
7
To change the value of any item in the array we use the same syntax with the square brackets and assign a new value to it.
names[0] = 'Tyrion'; //changes element zero from Jon to Tyrion
names[6] = 'Reese'; //adds a new element to the array at the 7th position
2
3
# Pop, Push, Shift, Unshift
If you want to add a new element to or remove an element from either the beginning or the end of the Array then we can
use the pop
, push
, shift
or unshift
methods.
Picture the Array as a stack of Lego bricks. Element zero was the first one added and it sits at the bottom of the
stack. The element on top was the last one added. The pop
method will remove an element from the top. The push
method will add a new element on the top.
The crude analogy used to remember the other two methods is - taking a shift
will drop an element off the bottom of
the stack and unshift
will reverse that.
let removed1 = names.pop(); // remove the last element added
let removed2 = names.shift(); //remove the first element from the array
names.unshift(removed2); //put removed2 back at the start of the Array
names.push(removed1); //put removed1 back as the last element
2
3
4
5
You can call these methods repeatedly to remove everything from the Array, if you want.
# Array at method
A new method has been added recently for Arrays in JavaScript.
We already know that we can use the square brackets to target a specific element in an array. Inside the square brackets you put the index position of the element you want to access. Remember to start counting at zero.
let myarray = ['a', 'b', 'c'];
console.log(myarray[0]); //a
console.log(myarray[1]); //b
console.log(myarray[2]); //c
2
3
4
Now, we can use the .at()
method to target elements in the same way.
let myarray = ['a', 'b', 'c'];
myarray.at(0); //a
myarray.at(1); //b
myarray.at(2); //c
2
3
4
So, what is the point of this new method if we could already do this with the square brackets?
We can now use negative numbers to count from the end of the array too.
myarray.at(-1); //c
myarray.at(-2); //b
myarray.at(-3); //a
2
3
Instead of having to find out the length of the array and then calculate the position, we can use negative numbers to represent the counting backwards from the end.
# Slice and Splice
If you want to remove one or more elements from the middle of an Array you can use the slice
method. If you want to
add one or more elements to the middle of an Array you can use the splice
method.
The slice
method needs a starting index and an ending point. The starting index is a number for the position of the
first element to remove. The second number provided is the index to stop before. If negative numbers are used for either
value then count from the end of the Array. If no ending number is provided then it will remove from the starting
position to the end of the Array. The slice
method does NOT change the original array. It returns a copy of the
selected items.
The splice
method can be used to only insert new elements or to remove elements and replace them with a new series of
elements. It takes a starting position as the first argument. The second argument is how many elements to remove, which
may be zero. The third and all subsequent arguments will be inserted at the starting index. The splice
method will
change the original array.
let friends = ['Chandler', 'Pheobe', 'Julian', 'Bubbles', 'Rachel']; //elements 0, 1, 2, 3, 4
let start = 2; //start selecting at
let end = 3; //up to but NOT including
let removedFriends = friends.slice(start, end);
// slice() does not change the original array, it just returns the selected items
// removedFriends is now Julian
start = 2;
let numToRemove = 1;
let more = friends.splice(start, numToRemove, 'Joey', 'Monica', 'Ross');
//Bubbles removed and 'Joey', 'Monica', 'Ross' added
//friends is now 'Chandler', 'Pheobe', 'Joey', 'Monica', 'Ross', 'Rachel'
// splice() DOES change the original array
2
3
4
5
6
7
8
9
10
11
12
13
14
# ForEach Method
Once you understand what arrays are and how you can add and remove values from an Array, then you need to know how to
loop over the values. We already discussed the for...loop
and for...in
statements last week, and that works fine but
there are actually built-in methods designed to loop over Arrays for specific purposes.
If you want to loop through an array, there is a built-in method for doing so, called forEach
. The method has one
required parameter - a function. It will call this function once for each item in the Array.
When it calls the function, it will pass three things to the function.
- The item from the Array
- The index number of the current item.
- A copy of the Array which can be used to do comparisons.
The three items will ALWAYS come in that order. You can name the three variables whatever you like.
let beers = ['Corona', 'Headstock', 'Heineken'];
beers.forEach(function (item, index, arr) {
console.log(index, item);
});
/** outputs
0 Corona
1 Headstock
2 Heineken
**/
2
3
4
5
6
7
8
9
# Array Map
The map
method works similarly to the forEach
method. It loops once for each item in the Array. It calls a function
(which you provide) each time it loops. It provides the same three values to the function each time it is called.
The difference is that while the forEach
method returns undefined
, the map
method returns a NEW array built
out of the return values from the function it called.
Because it called the function once for each item in the Array, it means that the new Array will always be the exact same length as the original array.
let cheeses = ['Gouda', 'Cheddar', 'Brie'];
let newArr = cheeses.map(function (item, index, arr) {
return item.substr(1, 2); //return the 2nd letter from item
});
console.log(newArr); // ['o', 'h', 'r']
// Here is the Arrow function equivalent
let newArray = cheeses.map((item) => item.substr(1, 2));
2
3
4
5
6
7
8
# Array Filter
Just like the forEach method and the map method, the Array filter
method will loop through an array and call a
function once for each element in the array. The filter
method also returns a NEW array.
However, the difference between the map
and filter
methods is that the filter
method returns an array holding a
copy of the original array elements, and it is allowed to include or exclude elements from the original array as it
loops.
If the function called by the filter
method returns a falsey value then it excludes the current element. If it returns
a truthy value then it will include that element in the new array.
let cast = ['Archer', 'Pam', 'Krieger', 'Cheryl', 'Mallory', 'Lana', 'Ray'];
//we want to remove any name that is fewer than 6 characters
let newcast = cast.filter(function (item, index, arr) {
if (item.length > 6) {
return true;
} //else the function will return undefined which is a falsey value
});
// the newcast array will be ['Archer', 'Krieger', 'Cheryl', 'Mallory']
//Here is the arrow function equivalent
let newcast = cast.filter((item) => item.length > 6);
2
3
4
5
6
7
8
9
10
11
# Sorting Arrays
At some point you will want to sort an Array. Thankfully, the JavaScript array object comes with a built-in sort
method. The sort
method will change the original Array.
The sort will sort the items in the Array in alphabetical order.
let names = ['Bob', 'Linda', 'Tina', 'Louise', 'Gene'];
names.sort();
console.log(names); //the sorted version will be logged
2
3
if you want to sort the Array in numerical order or in some other custom way, you can pass a function to the method which will be used to sort the values. Watch this video to learn more.
# Other Array Methods
There are MANY array methods that are used routinely. Do not try to memorize them all. Get familiar with what the possibilities are. You will gain expertise in the methods over time, with practice. Revisit this list on a regular basis to review.
One thing to pay special attention to with Array methods is whether the method changes the original Array or whether it creates a new one. If the method changes the original Array then it is called a destructive method.
# Array.concat( )
The Array concat method allows you to add another Array on to the end of the original one. It returns a new Array.
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = arr1.concat(arr2); // [1,2,3,4,5,6]
2
3
# Array.includes( )
The Array includes method will loop through an Array looking for a match for the value that you provide. The value you
provide can be any Primitive. Optionally you can add a starting position to begin looping. It returns a true
or
false
value.
let arr1 = ['bob', 'mary', 'fred', 'alice'];
let arr2 = ['Bob', 'Mary', 'Fred', 'Alice'];
arr1.includes('Fred'); //false
arr2.includes('Fred'); //true
2
3
4
# Array.some( )
The Array some method will loop through the values in an Array and returns true
as soon as it finds the first value
that meets your condition. It accepts a function as it's parameter. This makes it very efficient because it could exit
before looping through all values.
let arr2 = ['Bob', 'Mary', 'Fred', 'Alice'];
arr2.some((name) => {
return name == 'Fred';
}); //true
2
3
4
# Array.every( )
The Array every method will check every value in an Array to see if they all meet a condition that you choose. It
returns a true
or false
.
let nums = [1, 3, 5, 7, 9, 15, 23];
//check if every number is odd
nums.every((num) => {
if (num % 2 == 1) {
return true;
} else {
return false;
}
});
2
3
4
5
6
7
8
9
# Array.join( )
The Array join method will convert all the values in the Array into Strings and then combine all the Strings into a single String. You have the option of putting a separator between each of the String values as their are joined.
let words = ['I', 'love', 'the', 'smell', 'of', 'napalm', 'in', 'the', 'morning'];
words.join(' '); // "I love the smell of napalm in the morning"
2
# Array.reduce( )
The Array reduce method will loop through an Array and return a single value. You provide a function and a starting value for comparison. The starting value is often called the accumulator.
//find the biggest number in an array that is positive
let nums = [-23, 45, -3, 0, 144, -42, 87];
let big = nums.reduce((acc, num) => {
if (num > 0 && num > acc) {
return num;
} else {
return acc;
}
}, 0);
2
3
4
5
6
7
8
9
# Reference
Full Array Video Playlist (opens new window)
MDN Array Object Reference for all methods (opens new window)
# What to do this week
TODO Things to do before next week.
- Read all the content from
Modules 4.1, 4.2, and 5.1
. - Re-Read
Module 5.1
- Review
Module 5.1
- Come up with some questions about the content in
Module 5.1
- Continue working on the Hybrid Exercises
- Submit Hybrid 3