3 minutes
Javascript 30 Day 4: Array Cardio Day 1
Today’s lesson was all about some really useful array functions in javascript: filter
, map
, sort
and reduce
. It also introduced console.table
as a great alternative to console.log for tabular data. It’s one of those things in console that I learned about long ago and probably forgot, but it’s great to be reintroduced. It got me to go re-look at all the other cool stuff you can do with the javascript console. I may need to do a writeup on those things at some point because they are great and I think mostly developers rely on just console.log
when there’s a whole lot more they could do and learn using their browser’s console.
As far as the exercise itself, I found it pretty straight-forward and simple, but I use these concepts and functions on a regular basis across a number of languages. There was one part about figuring out the boulevards in France that contain “de” which involved running some code in the console on a Wikipedia page, but that ended up being something you could “one-liner” as well. It seemed slightly out of place with the other exercises, but it combined a couple of concepts - the document.querySelector
and document.querySelectorAll
from previous days, along with a map
and a filter
call.
I did the exercises (except the Wikipedia one) on my own before watching the whole video. In most cases, what I came up with was either exactly what Wes showed, or the story was same, but the variable names were changed to protect the innocent. There were a few that we did differently though, and I’m now not sure if the way I did mine would end up with problems that I couldn’t think of. Specifically, there’s one with an array of strings representing people, and the strings are essentially Last name, First name
of a bunch of celebrity names. The exercise is to sort the list alphabetically by last name. I just sorted it in the format it was given, while Wes broke the string into last and first name by splitting the string on the ,
. I’m not sure if what I did would run into an issue under some circumstances, but if you think of a case where it would be wrong, I’d really like to know about it.
Other ones I did differently, there’s some that wanted you to sort a bunch of inventors based on how long they had lived. In Wes’ solution, he calculates the ages and then used a ternary to return either -1 or 1 based on which value was larger. For mine, I calculated the ages, but I just returned the value of subtracting the two which I think is still legitimate because I don’t think sort
needs to have only 0
, 1
or -1
values returned. I’m not sure one or the other is more readable, but I’m not the biggest fan of ternaries in a lot of cases. For simple sorts though, I’ve got no issue.
That’s about all I’ve got to say about Day 4. On to Day 5!