Using Arrays/Lists
So you have passengers in the bus, now what?
Let's search to see if "joe" is in the bus, (he didn't pay his bus fare).
const bus = ["driver", "seat", "seat", "me", "joe", "billy", "caboose"];
for (let i = 0; i < bus.length; i++) {
let passenger = bus[i];
if (passenger === "joe") {
return true;
}
}
return false;
This is the simplest search there is:
- Loop over all elements in the array
- Compare the element's value to something you want to find
- Return true if its found, otherwise return false once everything has been searched.
This is a called a Linear Search, and is where Big O notation comes into play.
Big O states the complexity (how hard the computer works to run the code) of an algorithm. In this case, Linear Search is O(N), where there can be a number of N people in the bus, and we check every person.
What if we want to find other people?
Let's make a function!
function findBusPassenger(busToSearch: string[], passengerToFind: string) {
for (let i = 0; i < busToSearch.length; i++) {
let currentPassenger = busToSearch[i];
if (currentPassenger === passengerToFind) {
return true;
}
}
return false;
}
Now we can search for anyone!
const foundJoe = findBusPassenger(bus, "joe");
if (foundJoe) console.log("Joe, you need to pay your bus fare!");
const foundBilly = findBusPassenger(bus, "billy");
if (foundBilly) console.log("Billy, you need to pay your bus fare!");
But what if I want to find Joe, and find who sits before and after him?
If you know how to index, it might seem as simple as saying [joe - 1] and [joe + 1], but what if joe is the driver, or if joe is the caboose? Then we can't simply index since it would break the array.