Module 3: Manipulating Arrays
Using the for loop
One of the most commonly used types of loops is simply called a
for
loop; which is different from a “for…in” or “for…of”
loop. for
loops allow you to repeat the same block of
code (or function) for a specified amount of times. So if you wanted
to repeat a code that prints out “Hello” ten times or a countdown from
10 to 0, you would use a for
loop. If you wanted to only
display the first ten items in an array, you would also use a
for
loop. And, to clarify, with a for
loop
you can also specify that you would like to iterate over all items in
an array, functioning much like a “for…in” loop. Here is the general
format of a for
loop:
for ([starting expression]; [condition]; [increment expression]) {}
We understand that this might look confusing at first, so let's look at an actual example before explaining what each part means:
for (let i = 0; i <= 10; i++) { // setting variable and parameters for looping through indices
console.log(i) // will print out 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
}
Wow, this may look very confusing at first glance, but it all really
boils down to this: everything within the parentheses after the
for
word is how you control the loop (or the parameters
you set), and everything in the curly brackets is what function you
want the loop to do.
Let's explain each part:
The first part contains the starting expression. Here
is when you will declare a variable, such as i
for
index
, and give that variable an initial value; this is
also why you use the word let
. This is the index where
the loop will start.
The second part contains the condition. This is where
you will use your variable, i
, and add a condition for
how long the code will run. As long as that condition remains truthy,
such as, as long as i
is less than or greater than 10,
your code will continue looping.
The third part contains the increment expression; and
this will determine how many you would like for your variable,
i
, to increase or decrease by after each loop has run,
such as i++
(shorthand for: increase by one each time.).
How to Build It
Your boss at “Pixel Perfect Studios” is trying to decide how many
images or videos should be rendered at once on a user's homepage.
You suggest that perhaps a good place to start is ten. You are given
a lengthy array (named imgCollection
) of random stock
photos to work with, so you draft up a “for” loop to only render the
first ten of that array:
const imgCollection = [ "img1Hyperlink", "img2Hyperlink", "img3Hyperlink", "img4Hyperlink", "img5Hyperlink", "img6Hyperlink", "img7Hyperlink", "img8Hyperlink", "img9Hyperlink", "img10Hyperlink", "img11Hyperlink", "img12Hyperlink", "img13Hyperlink", "img14Hyperlink", "img15Hyperlink", "img16Hyperlink", "img17Hyperlink", "img18Hyperlink", "img19Hyperlink", "img20Hyperlink", "img21Hyperlink" ] // sample created array
for (let i = 0; i < 10; i++) { // setting parameters to iterate first 10 indices
console.log(imgCollection[i]) // will print out the hyperlinks to the first 10 images in the image collection
}
Take notice that we didn't type i <= 10
for the
conditional statement. Remember that the first item in an array has
an index of 0. So the first ten items would be indices 0-9.
With ten listed items complete, it's now time for you to try and display the entire length of the array; which means, however many images a user has uploaded onto their account, that is how many images you want to immediately display on their user homepage. Using the same array as before, you add something new to your “for” loop to make this one work.
const imgCollection = [ "img1Hyperlink", "img2Hyperlink", "img3Hyperlink", "img4Hyperlink", "img5Hyperlink", "img6Hyperlink", "img7Hyperlink", "img8Hyperlink", "img9Hyperlink", "img10Hyperlink", "img11Hyperlink", "img12Hyperlink", "img13Hyperlink", "img14Hyperlink", "img15Hyperlink", "img16Hyperlink", "img17Hyperlink", "img18Hyperlink", "img19Hyperlink", "img20Hyperlink", "img21Hyperlink" ]
for (let i = 0; i < imgCollection.length; i++) { // set total length of of array as end point
console.log(imgCollection[i]) // will print out the hyperlinks to all images in the array
}
As used above, remember that using the .length
method
for an array will return the total number of items in that array.
Finally, you decide that you want to create a summary or portfolio of all the images of one user. You want this summary to be only a fifth of the images from their collection, but you don't want them to be the last fifth of the images they uploaded. You decide to make another loop that will print the hyperlinks to every fifth image, starting with the first one. So you are really pulling the first image, then the sixth, then eleventh, and so on until you reach the end of the array.
Here is what you do:
const imgCollection = [ "img1Hyperlink", "img2Hyperlink", "img3Hyperlink", "img4Hyperlink", "img5Hyperlink", "img6Hyperlink", "img7Hyperlink", "img8Hyperlink", "img9Hyperlink", "img10Hyperlink", "img11Hyperlink", "img12Hyperlink", "img13Hyperlink", "img14Hyperlink", "img15Hyperlink", "img16Hyperlink", "img17Hyperlink", "img18Hyperlink", "img19Hyperlink", "img20Hyperlink", "img21Hyperlink" ]
for (let i = 0; i < imgCollection.length; i += 5) { //starts at index "0"; loop up to the last image by 5s
console.log(imgCollection[i]) // prints "img1Hyperlink", "img6Hyperlink", "img11Hyperlink", "img16Hyperlink", "img21Hyperlink",
}
There are a few important things to clarify what you see here:
Notice how we have changed the increment expression from
i++
to i += 5
, thus returning every 5th
image. Finally, here we started with the first image, but let's say
you wanted to return every second or third image of every five
images. You can easily accomplish this by starting your index at 1
or 2, instead of 0.
Using the while loop
A while
loop is similar to the for
loop we
learned above; however many of the parameters for the loop are written
either before the loop or in the function of the loop, except for the
conditional statement. Finally, a while
loop will run for
as long as the condition remains truthy. Here is the format for a
while
loop:
let i = 0; // here we are declaring the index before the loop itself
while (i < 5) { // only setting the condition statement here
console.log(i); // will print 0, 1, 2, 3, 4
i++; // notice how the increment expression is now written in the function
};
How to Build It
Let's return to your assignment to draft several options for how many images should initially render on a user's homepage of their “Pixel Perfect Studios” app. Let's say you now found out that all the images are organized from oldest to newest. If you wanted to return the ten newest images you would need to return the last one and work backward like this:
const imgCollection = [ "img1Hyperlink", "img2Hyperlink", "img3Hyperlink", "img4Hyperlink", "img5Hyperlink", "img6Hyperlink", "img7Hyperlink", "img8Hyperlink", "img9Hyperlink", "img10Hyperlink", "img11Hyperlink", "img12Hyperlink", "img13Hyperlink", "img14Hyperlink", "img15Hyperlink", "img16Hyperlink", "img17Hyperlink", "img18Hyperlink", "img19Hyperlink", "img20Hyperlink", "img21Hyperlink" ]
let i = imgCollection.length - 1; // set initial index to the last index
while (i > imgCollection.length - 11) { // condition continue up to the 10th last image
console.log(imgCollection[i]); // will print out the hyperlinks to the last 10 images in the imgCollection array
i--;
};
As you can see, things are a little shuffled, but the logic of a
while
loop is very similar to a for
loop.
Conclusion
You have just learned how to use the two most common ways of looping
in code: the for
and while
loops. Although
they are usually used to loop through data, these two loops are
surprisingly flexible and can be used in many other circumstances. As
you get more comfortable with them, you will see many opportunities at
BloomTech and in your career where you can leverage the power of
loops.
Basic Array Methods
Arrays are a very useful tool when storing strings, numbers, or other values within a list; and using loops is a great way to iterate through items in an array. But what happens when you want to change the array itself? What if you wanted to add an item or take one out? Or what if you wanted to simply read part of the array, like the first three indices? As you can imagine, these actions, which we more accurately call methods in Javascript, are easily accessible as one-word shortcuts; and they are used so frequently when working with arrays that they deserve immediate attention here.
In this reading, you will learn about three of the most common methods
when working with arrays: push()
, pop()
, and
slice()
.
Using push to add elements to an array
The push()
method is an action that allows you to add
items to an array. You can add the push()
method simply
by chaining it (attaching it to the end) to the variable that holds
your array. For example:
const sampleArray = ["item1", "item2", "item3"] // example array
sampleArray.push("item4") // will add “item4” to the end of sampleArray
console.log(sampleArray) // prints out ["item1","item2","item3","item4"]
Furthermore, the push()
method also returns a value: the
new length of the array. A return value is a value that automatically
gets returned to the user by using this method. A user can store this
value in a variable that they can then call later, if they find it
useful.
const sampleArray = ["item1", "item2", "item3"]
const returnValue = sampleArray.push("item4")
console.log(returnValue) // prints out 4
Finally, it is worth noting here that when you add an item into an
array using the push()
method, you are adding it to the
end of the array. If you wanted to add items to the beginning of the
array, you would use the same process but with the
unshift()
method. The unshift()
method is
indeed useful and worth knowing, but will not be revisited in the rest
of this lesson.
How to Build It
The time has come for you to add a new entry from the latest daily recordings of the future olympian's 100m dash times. Here is what you documented already since the runner has adopted their new workout program:
const runTimes = [ 10.59, 10.67, 10.52, 10.48 ]
Now it is time for you to add the latest time of 10.56:
runTimes.push(10.56)
console.log(runTimes) // prints out [10.59,10.67,10.52,10.48,10.56]
Finally, the coach now wants to add another time of 10.68 and would also like to get an update of how many trials their runner has had under the new workout program. Remember that the push() method returns a value and that value is the new length of the updated array. Thus, when adding on to the example above:
const runTimes = [ 10.59, 10.67, 10.52, 10.48, 10.56 ] // updated run times
const totalTrials= runTimes.push(10.68); // add another run time of 10.68
console.log(totalTrials); // prints out 6
Using pop to remove elements from an array
Very similar in how the push()
method is used, but
opposite in purpose, the pop()
method removes the last
item from an array.
const sampleArray = ["item1", "item2", "item3"] // sample array
sampleArray.pop() // will remove the last item, “item3”, from the sampleArray
console.log(sampleArray) // prints out ["item1","item2"];
Furthermore, pop()
also returns a value, but not the
length of the new array like push()
did. Instead,
pop()
returns the value of the item you just removed.
const sampleArray = ["item1", "item2", "item3"] // sample array
const returnValue = sampleArray.pop() // saving return value of “.pop()” method
console.log(returnValue) // prints out "item3"
How to Build It
Let's return to our scenario with the olympian who you are tracking daily run times under their new workout routine. Let's say you recently received an array for this week's run times:
const runTimes = [10.45, 10.55, 10.63, 10.58, 11.58]
You notice that the last run time was an entire second longer than a rough average of the ones before it. So, you and your employer contact the coach to inquire about the discrepancy. You receive word that the “11.58” time came about on the heels of the runner coming down with the flu. Since it is an outlier, they would like you to remove it from the array. Here is how that would look:
runTimes.pop() // removes last run time of 11.58
And let's say they still would like you to save that time anyway (for record-keeping) but in a separate variable. This would look like this:
const runTimes = [10.45, 10.55, 10.63, 10.58, 11.58]
const slowTime = runTimes.pop()
console.log(slowTime) // will print 11.58
Obtaining subarrays with slice
A third and very commonly used method for arrays is
slice()
. slice()
can be used to copy a
section of items within an array, as long as you know their indices.
slice()
will return a new array of what you specified to
copy. slice()
can take a few variations of parameters
(options) to help you copy exactly which indices you want from the old
array. Let's see how a simple slice()
method works by
only specifying a “start” and “end” index:
const sampleArray = ["item1", "item2", "item3", "item4", "item5"]
const slicedArray = sampleArray.slice(1, 4) // starts at index 1 up to index 4
console.log(slicedArray) // will print out [“item2”, “item3”, “item4”]
Note that we used two parameters in this example: (1, 4). The first parameter, “1”, is the “start” index. This is the position or index you want to start copying from the existing array. The second parameter, “4”, is the “end” index, this is the index you want to copy up to from the existing array but do not want to include. In other words, the first, starting index is “inclusive” and gets included in the new array, while the second ending index is “exclusive” and gets excluded from the new array.
Now let's talk about return values. Unlike the
push()
and pop()
methods,
slice()
does not change the existing array. Instead, the
returned value when using the slice()
method is the new,
sliced array. Thus, to access the sliced array, you will need to save
it to a variable when using it, as you see in the example above.
How to Build It
Back to our sports data, the coach would now like to compare the first five trials with the last five to see if there has been any overall improvement over time. Here is what we would then do to get the first five trial times and save it to a new variable:
const runTimes = [10.45, 10.56, 10.67, 10.34, 10.45, 10.78, 10.34, 10.45, 10.45, 10.34, 10.24, 10.25, 10.45, 10.34, 10.33]
const firstFiveTrials = runTimes.slice(0, 5)
console.log(firstFiveTrials) will print [10.45, 10.56, 10.67, 10.34, 10.45]
Getting the last five trial times would require us to work backwards
by specifying index location using negative numbers. Using a
negative number, like “-2”, will count two positions backward from
the end of an array. Also, since the “end” index will be the end of
the array, you no longer need to include it in the parameters. Here
is what that looks like using the
slice()
method using the same “runTimes” listed above:
const lastFiveTrials = runTimes.slice(-5) // ”-5” is the start index; no end index needed
console.log(lastFiveTrials) // will print [10.24, 10.25, 10.45, 10.34, 10.33];
Using indexOf to get the index of an element
Continuing from the concept of manipulating arrays with slice(),
another fundamental method to understand is indexOf()
.
The indexOf()
method in JavaScript is used to find the
index of the first occurrence of a specified element in an array. If
the element is not found, it returns -1. This method is especially
useful when you need to know the position of an element before
performing operations like slicing or splicing.
Here's a simple example to illustrate how
indexOf()
works:
const fruits = ["apple", "banana", "cherry", "date", "elderberry"];
const cherryIndex = fruits.indexOf("cherry"); // finds the index of "cherry"
console.log(cherryIndex); // will print 2, as "cherry" is at index 2 in the array
const missingFruitIndex = fruits.indexOf("fig"); // tries to find "fig", which is not in the array
console.log(missingFruitIndex); // will print -1, as "fig" is not found
In this example, we have an array fruits
. When we use
indexOf()
to find the index of "cherry", it returns 2,
because "cherry" is the third element in the array (remember, array
indices start at 0). However, when we look for "fig", which is not in
the array, indexOf()
returns -1.
How to Build It
Building on our understanding of array manipulation with
slice()
, let's explore a practical case study using
indexOf()
. Imagine the coach wants to analyze the data
starting from a specific trial time, say the first occurrence of a
10.34 second run. Instead of manually searching through the
runTimes
array, indexOf()
can be used to
find the index of the first 10.34 second run efficiently.
Here's how we could implement this:
const runTimes = [10.45, 10.56, 10.67, 10.34, 10.45, 10.78, 10.34, 10.45, 10.45, 10.34, 10.24, 10.25, 10.45, 10.34, 10.33]
const firstOccurrenceIndex = runTimes.indexOf(10.34) // finds the first occurrence of 10.34
console.log(firstOccurrenceIndex) // will print 3, as the first 10.34 is at index 3
// Assuming the coach wants to compare all times after this including the current one:
const timesAfterFirstOccurrence = runTimes.slice(firstOccurrenceIndex)
console.log(timesAfterFirstOccurrence) // will print [10.34, 10.45, 10.78, 10.34, 10.45, 10.45, 10.34, 10.24, 10.25, 10.45, 10.34, 10.33]
In this case study, indexOf()
is used to locate the
first instance of the 10.34 second run. Once this index is found, we
can then use slice()
to create a new array starting
from this point. This method allows the coach to quickly isolate and
analyze the segment of data from the first 10.34 second run onwards,
providing a more targeted approach to data analysis.
Conclusion
Being able to manipulate arrays using pop
,
push
, slice
, and indexOf
will
come in handy on many projects, both here at BloomTech and in your
career. In fact, these functions are all you need to complete nearly
any task requiring manipulating arrays. As you continue practicing
manipulating arrays, these functions will become second nature to you.
So keep on practicing!
Guided Project
In this guided project, you will see examples of concepts that every developer should understand when working with arrays in Javascript. A lot of the data you'll be working with on the job will be in arrays, and working creatively and efficiently with arrays is a skill every software engineer should have. The instructor will cover forwards and backward looping, skipping elements while looping, building nested loops, popping elements from an array, and slicing arrays. These commonly used concepts will help you manipulate data into valuable information, making this guided project an essential resource for tackling complex programming challenges.
The For and While Loops
As you have learned, the for…in
loop is a very useful
tool when you want to loop through all indices (items) in an array or
properties in an object; but what if you didn't want to loop through
all the items or properties. Is there a way you can set parameters to
only loop through some of the list, say the first 10 items or
properties? Absolutely! In reality, web applications often need to
handle arrays and objects that are thousands of items long. Displaying
them all at once could cause the application to become overburdened
and cause a very slow user experience.
Two of the most commonly used loops for setting parameters, or limits,
when iterating over arrays and objects are the
for
loop, and the while
loop. In this
reading, you will learn about their similarities, differences, and
when one is preferred over another.
Module 3 Project: Manipulating Arrays
This module project will let you practice using for and while loops, and manipulating arrays (with pop, push, and slice) in Javascript. These concepts are essential for iterating through data and making changes to arrays, and without them, coding can become time-consuming and repetitive. However, with a proper understanding of how to use loops and these array methods, you will be able to write more efficient, dynamic, and concise code that can handle larger datasets and perform complex operations.
The module project contains advanced problems that will challenge and stretch your understanding of the module's content. The project has built-in tests for you to check your work, and the solution video is available in case you need help or want to see how we solved each challenge, but remember, there is always more than one way to solve a problem. Before reviewing the solution video, be sure to attempt the project and try solving the challenges yourself.
If you can successfully get through all the Module Projects in a sprint, you are ready for the Sprint Challenge and Sprint Assessment, which you must pass to move on to the next Sprint.
Instructions
The link below takes you to Bloom's code repository of the assignment. You'll need to fork the repo to your own GitHub account, and clone it down to your computer:
Starter Repo: Manipulating Arrays
- Fork the repository, and then use the green button and your terminal to clone the project down to your computer.
-
Next, open the
index.html
file in both VSCode and the Chrome Browser. VSCode is where you will make code changes, and Chrome is where you will check if your code is passing all the tests. - To check the tests, right-click on a Chrome window, select "Inspect," and ensure the console is visible. Then return to VSCode and start coding a solution to the first challenge. When you want to check if your code is correct, go to Chrome and refresh the page to run the tests and see your results.