In this lab, we cover arrays. Learn how to store large amounts of data in a data structure and iterate through it.
The problems are written as code comments //, which means they won't be executed by JavaScript. Make sure to run your code after each attempt to make sure you don't have any bugs!
Open LabFiveChallenges.js in your text editor and solve the challenges listed. Refer to the reference section for help.
Declare and store data in arrays
Access array data by index
Modify array data by index
Multi-dimensional arrays
Array methods: push() and pop()
Array properties: length
Strings as arrays
Imagine walking into a bookstore with the intention of buying a specific book. How would you find it?
Naturally you'd head in the direction where you'd expect that book to be.
If you're into mystery, you'd go to the mystery section.
If you're into a certain author, you'd look for their name alphabetically.
The key feature of the bookstore that helps you find the book you seek is called a bookshelf. Bookshelves help structure books into manageable collections. Doing so makes it easy to find, store and retrieve the books within them.
In the world of programming, if books can be considered data, then bookshelves are data structures.
A data structure is a programming tool that allows for data to be efficiently stored and retrieved within collections of related program data. There are many different data structures, each with specific purposes in mind.
Organizing books into shelves is a relatively simple task that solves a potentially huge problem: piles of books all over the place, with no rhyme or reason to them. When we place books onto a shelf, we are organizing them in a linear sequence, from left to right. Each book has a "place" on the shelf, which is between two other books, or at the beginning or end of the shelf.
Additionally, if we take the extra step and sort the bookshelf (e.g., alphabetically by author), we can store and retrieve books in the sequence by scanning our eyes from left to right, or perhaps starting in the middle and narrowing our search down from there.
An array is a linear data structure similar to a bookshelf. Individual items in the array are called elements and can be accessed through their zero-indexed position in the array.
In JavaScript, arrays can be assigned to variables, or passed to/returned from functions. JavaScript arrays are signified by brackets [], and each element within an array is comma-separated. Arrays can even contain other arrays! (These are called 2D arrays.)
Examples:
let empty = [];
let notEmpty = [2, 4, 6, 8, 10, 12];
let nums = [2, 4, 6, 8, 10, 12];
let booleans = [true, false, true, true, false];
let strings = ['Code', 'Next'];
let programs = [['Web Dev Club', 'Robotics Club'], ['AI Bootcamp', 'Pitching Bootcamp']];
Although JavaScript doesn't enforce it, you should make each array homogeneous, or containing just one type of data (e.g., all strings, all numbers, etc).
The dot operator can be used with arrays, accessing their various methods and properties.
Use this to retrieve an element from an array at index i.
array[i]
Try it out:
> bookshelf[1]
'Invisible Man'
> bookshelf[0]
'Like Water for Chocolate'
> bookshelf[2]
'The Republic'
Remember: arrays, just like strings, are zero-indexed! And just as with strings, this is what happens when we try to access an element out of the bounds of the array:
> bookshelf[3]
undefined
Use this if you wish to replace the value of the element at array[i] with x.
array[i] = x
Try it out:
> bookshelf[2] = "Republic, The";
'Republic, The'
> bookshelf
[ 'Like Water for Chocolate', 'Invisible Man', 'Republic, The' ]
What happens when we try to replace an element that's out of bounds? Let's try replacing the value of bookshelf[5], which doesn't exist.
> bookshelf[5] = "Journey to the West"
'Journey to the West'
> bookshelf
[ 'Like Water for Chocolate',
'Invisible Man',
'Republic, The',
<2 empty items>,
'Journey to the West' ]
It looks like JavaScript simply creates that element at the specified index, and fills in the indexes up to that element with "empty items". What exactly are those?
> bookshelf[3]
undefined
Ah, we should have known. They haven't been defined yet, so they're undefined placeholders.
Consider this example where the variable passed into a function is passed by value:
let bar = 123; // global scope
function foo(num) {
num = 321; // local scope
}
foo(bar);
console.log(bar); // prints 123
This works the way it does because JavaScript primitive data types are passed by value. This means that when a variable is passed into a function, the value of that variable is passed, not the variable itself. In other words, when we call foo(bar) we are passing 123, not bar, into the function foo(). This is why bar remained unchanged when we printed it at the end.
Arrays (and objects, as you'll see later) are a different passed by reference. This means when the array is passed into the function, it's not actually the array itself getting passed, but a value representing the location of array in your computer's memory.
let bar = [1, 2, 3]; // global scope
function foo(nums) {
nums[0] = 3; // nums is local scope, but nums[0] refers to bar[0]
nums[1] = 2;
nums[2] = 1;
}
foo(bar);
console.log(bar.toString()); // prints "3,2,1"
Thus, nums[0] refers to the same location in memory that bar[0] does, which makes it possible to modify it like we did above.
This method adds any number of elements to the end of the array, then returns the new length of the array.
array.push(element1, element2, element3...)
Example: If bookshelf started as an empty array:
> bookshelf.push('Like Water for Chocolate');
1
> bookshelf.push('Invisible Man', 'The Republic');
3
This method removes and returns the last element in the array. Note that each time we called bookshelf.pop(), the removed element is displayed as a return value. This is because array.pop() removes and returns the last item of an array.
array.pop()
Example:
> bookshelf
[ 'Like Water for Chocolate', 'Invisible Man', 'The Republic']
> bookshelf.pop();
'The Republic'
> bookshelf
[ 'Like Water for Chocolate', 'Invisible Man']
This method allows you to insert or remove multiple elements anywhere within an array, not just the end (like array.push() and array.pop()).
array.splice(start, number of elements to remove, element(s) to be added)
start: The index where you want the element insertion to begin. Whatever element is already there will either be erased (see next argument) or shifted to the right.
number of elements to remove: The number of elements after the insertion that you'd like to remove. If you don't want to remove anything, make this 0.
element(s) to be added: The element or elements you'd like to insert, if any. This is optional (see below).
Example: Here, the splice function is being used to add 'Journey to the West' and remove 'Invisible Man'
> bookshelf.splice(1, 0, 'Journey to the West');
[]
> bookshelf
[ 'Like Water for Chocolate', 'Journey to the West', 'Invisible Man', 'The Republic' ]
> bookshelf.splice(2, 1);
[ 'Invisible Man' ]
> bookshelf
[ 'Like Water for Chocolate', 'Journey to the West', 'The Republic' ]
Not to be confused with array.splice()!
This method returns a section of an array from startIndex and up to but not including endIndex, or from startIndex to the end of the array if no second argument is provided. Note that this returns a new array and does not modify the original in any way.
array.slice(startIndex, endIndex)
Example:
> let newShelf = bookshelf.slice(0);
> newShelf
[ 'Invisible Man', 'Journey to the West', 'Like Water for Chocolate', 'The Republic' ]
> let firstTwo = bookshelf.slice(0, 2);
> firstTwo
[ 'Invisible Man', 'Journey to the West' ]
This method sorts an array from least to greatest values, or alphabetically.
array.sort()
Example:
> bookshelf.sort();
[ 'Invisible Man', 'Journey to the West', 'Like Water for Chocolate', 'The Republic' ]
This method returns the index of the first instance (read left to right) of the input searchElement in an array. If searchElement does not exist in array, this method returns -1 instead.
The second argument startIndex is optional. It is a number specifying the index where the search for searchElement should begin. If you do not specify a second argument, its default value is 0 (i.e., start search from beginning of the array).
array.indexOf(searchElement, startIndex)
Example:
> bookshelf.indexOf("Like Water for Chocolate");
2
> bookshelf.indexOf("Harry Potter");
-1
The length property holds the length of an array.
array.length
Example:
> bookshelf
[ 'Like Water for Chocolate', 'Journey to the West', 'Invisible Man', 'The Republic' ]
> bookshelf.length
4
This method converts an array to string format, without brackets. This can be useful for printing.
array.toString()
Try it out:
> bookshelf
[ 'Like Water for Chocolate', 'Invisible Man', 'The Republic' ]
> bookshelf.toString();
'Like Water for Chocolate','Invisible Man','The Republic'
The includes() method can be called on a string to determine if the string contains the characters that were passed into the function.
The function will return True if the characters is a substring and False if not found.
let item = "almond milk"
if(item.includes("milk")){
//Return error
}
else {
//Add item to the shopping list
}