JavaScript Arrays
2018-03-18
Here is everything I know about JavaScript arrays so far. This post will get updated the more that I learn.
In this post:
- Create an array
- Access an array
- Loop over an array
- Add to an array
- Remove from an array
- Find the index of an array item
- Copy an array
- Nested arrays
- Array of objects
Create an array
let alphabet = [] # array literal notation
let alphabet = ["A"] # declared/initialized array
let alphabet = ["A", "B", "C"] # a three item array
Access an array using an index; arrays are zero-indexed
# starting array
let alphabet = ["A", "B", "C"]
alphabet[0] # output: A, the first index is always index = 0
alphabet[1] # output: B
alphabet[2] # output: C
alphabet[3] # output: D is an invalid index because the array item does not exist
Loop over an array: for-loop, forEach loop
# starting array
let alphabet = ["A", "B", "C"]
# for loop
for (let i = 0; i < alphabet.length; i++) {
console.log(alphabet[i])
}
# forEach loop
alphabet.forEach((item) => console.log(item))
Add to an array
# starting array
let alphabet = ["A", "B", "C"]
alphabet.unshift('Z') # add item to the start
# result: ["Z,""A", "B", "C"]
alphabet.push('D') # add item to the end
# result: ["Z", "A", "B", "C", "D"]
Remove from an array
# starting array
let alphabet = ["Z", "A", "B", "C", "D"]
alphabet.shift() # remove the first item
# result: ["A", "B", "C", "D"]
alphabet.pop() # remove the last item
# result: ["A", "B", "C"]
Find the index of an array item
# starting array
let alphabet = ["A", "B", "C"]
alphabet.indexOf("B") # output: index is 1
Nested arrays
# starting array
let nested = [
[1, 2, "A"],
[3, 4, 5, "B"],
[6, 7, 8],
[9, "C"]
]
# access the array
nested[0][2] # output: A
nested[1][3] # output: B
nested[2][4] # output: undefined
nested[3][1] # output: C
Array of objects
# starting array
let arrayOfObjects = [
{id: 100, alphabet: "A"},
{id: 101, alphabet: "B"},
{id: 102, alphabet: "C"}
]
# access an object value
arrayOfObjects[0]["alphabet"] # output: A
arrayOfObjects[1]["id"] # output: 101
arrayOfObjects[2]["alphabet"] # output: C