Learn
Arrays
.insert() and .remove() Methods

Previously, we learned how to add an item to the end of the array, but how do we add an item in the middle or even the start? And how do we remove an item?

Suppose we have an array:

var moon = ["πŸŒ–", "πŸŒ—", "🌘", "πŸŒ‘"]

To insert an item in the array at a specified index, we can call the .insert() method.

moon.insert("πŸŒ•", at: 0) // ["πŸŒ•", "πŸŒ–", "πŸŒ—", "🌘", "πŸŒ‘"]

The .insert() method takes two values:

  • The value to be inserted.
  • The at: and the index of the insertion.

So the code above inserted "πŸŒ•" at index 0.


To remove an item from the array, call the array’s .remove() method:

moon.remove(at: 4) // ["πŸŒ•", "πŸŒ–", "πŸŒ—", "🌘"]

The .remove() method only takes in one value, at: and the index of removal.

So the code above removed "πŸŒ‘" at index 4.

Instructions

1.

In the code editor, we have an array called dna with three-letter codes of nucleotides, also known as codons.

Insert "GTG" at index 3.

2.

Remove the item at index 0.

3.

What does the array look like now?

Print dna to find out.

Folder Icon

Take this course for free

Already have an account?