0% found this document useful (0 votes)
96 views8 pages

Udacity Array Splice

Uploaded by

Tesfaye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views8 pages

Udacity Array Splice

Uploaded by

Tesfaye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Splice

splice() is another handy method that allows you to add and remove elements from
anywhere within an array.

While push() and pop() limit you to adding and removing elements from the end of an
array, splice() lets you specify the index location to add new elements, as well as the
number of elements you'd like to delete (if any).

const donuts = ["glazed", "chocolate frosted", "Boston creme",


"glazed cruller"];
donuts.splice(1, 1, "chocolate cruller", "creme de leche"); //
removes "chocolate frosted" at index 1 and adds "chocolate
cruller" and "creme de leche" starting at index 1

Returns: ["chocolate frosted"]


donuts array after calling the splice() method: ["glazed", "chocolate cruller", "creme de leche",
"Boston creme", "glazed cruller"]

Following is the syntax of splice() method: arrayName.splice(arg1, arg2,


item1, ....., itemX); where,

 arg1 = Mandatory argument. Specifies the starting index position to add/remove items.
You can use a negative value to specify the position from the end of the array e.g., -1
specifies the last element.
 arg2 = Optional argument. Specifies the count of elements to be removed. If set to 0, no
items will be removed.
 item1, ....., itemX are the items to be added at index position arg1

splice() method returns the item(s) that were removed.

Note - This video does not have an audio. It was created as a visual to aid learning.

splice() is an incredibly powerful method that allows you to manipulate your arrays in a
variety of ways. Any combination of adding or removing elements from an array can all be done
in one simple line of code.

Take a look at the MDN documentation(opens in a new tab) to see a long list of example code
snippets demonstrating the power of splice() and then try the next set of programming
quizzes.

Quiz Question

We’ve decided to replace some of the donuts in the donuts array.


const donuts = ["cookies", "cinnamon sugar", "creme de leche"];

donuts.splice(-2, 0, "chocolate frosted", "glazed");

What does the donuts array look like after the following changes?

Thanks for completing that!

When you need to add and remove elements from an array at the same time, splice() is a
great option!

Quiz: Colors of the Rainbow

Directions:

James was creating an array with the colors of the rainbow, and he forgot some colors. The
standard rainbow colors are usually listed in this order:

const rainbow = ["Red", "Orange", "Yellow", "Green", "Blue",


"Purple"];

but James had this:

const rainbow = ["Red", "Orange", "Blackberry", "Blue"];

Using only the splice() method, insert the missing colors into the array, and remove the color
"Blackberry" by following these steps:

1. Remove "Blackberry"
2. Add "Yellow" and "Green"
3. Add "Purple"

Running Your Code

Enter the following in the terminal:

node rainbow.js
When your code runs, you should get this output:

[ 'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple' ]

Start Workspace

After starting your workspace, remember to keep the page open. Closing the page will shut down
the workspace and halt any associated processes.

Try the quiz on your own first. If you get stuck you can check the solution by clicking the button
below.

Here is one of the possible solutions:


const rainbow = ["Red", "Orange", "Blackberry", "Blue"];
// From index position 2, remove 1 element. Afterwards, add all
the elements mentioned in the argument.
rainbow.splice(2, 1, "Yellow", "Green");
// From index position 5, remove 0 elements. This means, no
removal of any element.
// Afterwards, add all the elements mentioned in the argument.
rainbow.splice(5, 0, "Purple");
// Did you noticed that the above method call is equivalent to
adding an element at a specific index in the array?
//Print
console.log(rainbow);

Output

['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple']

Quiz: Quidditch Cup

In the Harry Potter(opens in a new tab) novels, children attending the Hogwarts School of
Witchcraft and Wizardry(opens in a new tab) belong to one of four houses: Gryffindor,
Hufflepuff, Ravenclaw, or Slytherin. Each year, the houses assemble a Quidditch(opens in a new
tab) team of seven players to compete for the coveted Quidditch Cup. Your task is to help the
coach determine if the team has enough players.

Directions:

Create a function called hasEnoughPlayers() that takes the team array as an argument
and returns true or false depending on if the array has at least seven players.

Test your code with the following teams:


const team1 = ["Oliver Wood", "Angelina Johnson", "Katie Bell",
"Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry
Potter"];
const team2 = ["George Weasley", "Fred Weasley", "Harry
Potter"];
const team3 = [];
const team4 = ["Oliver Wood", "Angelina Johnson", "Katie Bell",
"Alicia Spinnet", "George Weasley", "Fred Weasley", "Harry
Potter", "Hermione Granger", "Ron Weasley", "Neville
Longbottom"];

Running Your Code

Enter the following in the terminal:

node quidditch.js

When your code runs, you should get this output:

true
false
false
true

Start Workspace

After starting your workspace, remember to keep the page open. Closing the page will shut down
the workspace and halt any associated processes.

Try the quiz on your own first. If you get stuck you can check the solution by clicking the button
below.

Here is one of the possible solutions:

const team1 = ["Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George
Weasley", "Fred Weasley", "Harry Potter"];

const team2 = ["George Weasley", "Fred Weasley", "Harry Potter"];

const team3 = [];

const team4 = ["Oliver Wood", "Angelina Johnson", "Katie Bell", "Alicia Spinnet", "George
Weasley", "Fred Weasley", "Harry Potter", "Hermione Granger", "Ron Weasley", "Neville
Longbottom"];
function hasEnoughPlayers(arrayInstance) {
if (arrayInstance.length >= 7) {
return true; // true is a boolean value. Do not return a
string "true"
} else {
return false; // false is also a boolean value. Do not
return a string "false"
}
}
console.log(hasEnoughPlayers(team1)); // should be true

console.log(hasEnoughPlayers(team2)); // should be false

console.log(hasEnoughPlayers(team3)); // should be false

console.log(hasEnoughPlayers(team4)); // should be true

Output

true

false

false

true

Quiz: Joining the Crew

Directions:

In an earlier exercise, you created a crew array to represent Mal’s crew from the hit show
Firefly.

const captain = "Mal";


const second = "Zoe";
const pilot = "Wash";
const companion = "Inara";
const mercenary = "Jayne";
const mechanic = "Kaylee";

const crew = [captain, second, pilot, companion, mercenary,


mechanic];

Later in the show, Mal takes on three new crew members named "Simon", "River", and
"Book". Use the push() method to add the three new crew members to the crew array.
const doctor = "Simon";
const sister = "River";
const shepherd = "Book";

Running Your Code

Enter the following in the terminal:

node join.js

When your code runs, you should get this output:

['Mal', 'Zoe', 'Wash', 'Inara', 'Jayne', 'Kaylee', 'Simon',


'River', 'Book']

Note: your output may look different because of the way the terminal prints out the array.

Start Workspace

After starting your workspace, remember to keep the page open. Closing the page will shut down
the workspace and halt any associated processes.

Try the quiz on your own first. If you get stuck you can check the solution by clicking the button
below.

Here is one of the possible solutions:


const captain = "Mal";
const second = "Zoe";
const pilot = "Wash";
const companion = "Inara";
const mercenary = "Jayne";
const mechanic = "Kaylee";

const crew = [captain, second, pilot, companion, mercenary,


mechanic];

const doctor = "Simon";


const sister = "River";
const shepherd = "Book";

// your code goes here

crew.push(doctor); // "Simon" gets added at the end of the array


crew.push(sister); // "River" gets added at the end of the array
crew.push(shepherd); // "Book" gets added at the end of the
array
console.log(crew);

Output

['Mal', 'Zoe', 'Wash', 'Inara', 'Jayne', 'Kaylee', 'Simon',


'River', 'Book']

Quiz: Checking out the Docs


Question 1 of 4

Use the MDN Documentation(opens in a new tab) to determine which of these methods would
be best for reversing elements in this array:

const reverseMe = ["h", "e", "l", "l", "o"];

Thanks for completing that!

You got it! Here's the code you could write to reverse the array above:

reverseMe.reverse();

Returns: [ 'o', 'l', 'l', 'e', 'h' ]


Thanks for completing that!

Yep, the sort() method can sort an array.

sortMe.sort();

Returns: [1, 10, 2, 6, 7]

Did you notice that 10 appears before 2? Traditionally, the number 2 comes before 10. But in the
.sort() method, numbers are converted to Unicode strings, so 10 comes before 2 in Unicode
order.

You might also like