Arrays in Javascript
In our last class we looked at strings. As we found out, a string in Javascript is more or less just a list of characters. But what if we want another kind of list? Say, a list of numbers, or a list of lists?
In Javascript (and most other languages) these types of lists are called arrays. In Javascript we can store any other type of variable in an array and can mix and match the types which we store.
// an array of numbers
let myArray = [1,2,3,4,5]
console.log(myArray)
// an array of strings
myArray = ['a','b','c','d','e']
console.log(myArray)
// an array of arrays (also known as a 2d array)
myArray = [[0,1],[2,3],[4,5]]
console.log(myArray)
// an array of mixed types
myArray = ['a', 0, [0,1,2]]
Arrays are useful any time you want to make or maintain a list of items. Just like a string, you can reference different elements of the array by index.
You can also add and remove elements at the end of the array using the push
and pop
methods. push
adds an element to the end, while pop
removes one.
// create an array of numbers 1-5
let myArray = []
for (let i = 0; i < 5; i++) {
myArray.push(i)
}
console.log(myArray)
console.log(myArray[3])
console.log(myArray.length)
while (myArray.length > 0) {
myArray.pop()
}
It's also easily possible to add and remove items at the start of an array by using the .shift()
and .unshift()
methods. shift
removes an element, while unshift
adds one or more.
let myArray = []
for (let i = 0; i < 5; i++) {
myArray.unshift(i)
}
console.log(myArray)
console.log(myArray.shift())
while (myArray.length > 0) {
console.log(myArray.shift())
}
Exercise 1
- Write a script to turn a string into an array of single characters.
e.g.
"hello"
=>['h','e','l','l','o']
- Write a script to reverse an array without using the built-in
.reverse()
method. - Let the user input
n
. Calculate the fibonacci sequence up to then
th term (indexing from 0) and print the resulting array. The first and second terms of the sequence are both equal to 1. For example, inputting 7 should output[1, 1, 2, 3, 5, 8, 13]
Useful Array Operations
Just like strings, we can concatenate two arrays by using the concat
function.
// create an array of numbers 1-5
let array1 = [0,1,2,3]
let array2 = [4,5,6,7]
let joined = array1.concat(array2)
console.log(joined)
A common thing we might want to do is turn a list into a string or a string into a list.
This is easily done with the join and split methods.
let array1 = ['hello', 'there', 'fellow', 'kids']
// join (CHARACTERS TO USE)
let joined = array1.join(' ')
console.log(joined)
let toSplit = "0 1 2 3 4 5 6 7 8 10"
// splits on the character in the parentheses, in this case space
let split = toSplit.split(" ")
console.log(split)
There are also several different ways of looping through arrays, each with their own advantages and disadvantages.
let array1 = [0,1,2,3]
// old-school; verbose but gives us most control
for (let i = 0; i < array1.length; i++) {
console.log(array1[i])
}
// modern, clean method; no index access
for (const el of array1) {
console.log(el)
}
// functional approach; can't use break effectively
array1.forEach( (el, i) => {
console.log(`${i}: ${el}`)
})
Exercises
- Take a list of numbers as a string from the user, and convert it into an array.
- Let the user input a space-separated list of numbers; return the sum, largest number, smallest number, and mean averages of that list.
- Users will input a width and a height for a 2d matrix. They are then prompted to enter lists of values separated by a space for each row of the matrix. Finally, the program calculates the sum of each row and each column of the matrix and prints these out next to the matrix.