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
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.
Remove the item at index 0.
What does the array look like now?
Print dna
to find out.