Originally posted on my blog
For the last several weeks I've been applying for jobs. Sadly, the startup I was working at just didn't work out. I am super bummed it didn't work out, but that's how things go sometimes. Anyway, I've been posting on twitter that I'm looking around and such and I had a friend offer to do a mock interview.
Short story, he absolutely roasted me.
I'm so thankful that we did that, because I've honestly never been asked technical questions in an interview like that. I just cracked under the pressure. I wasn't that I don't know how to reverse a list. I just couldn't remember how to do it on demand.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
You have an array, and you need to do something to every element. That's what map is for!
let numbers = [1,2,3,4,5] numbers = numbers.map(numb=> numb+1) console.log(numbers) // will be [2,3,4,5,6]
The big hurdle for me initially with any of this was realizing that
numb was totally made up. You can call it anything you want. Common practice is to call the
array the plural of whatever is contained in your array, and the singular item for each computation. I'll be honest, lots of this clicked for me by using a
forEach() for a long time, instead. The difference between them is
.map() returns an updated array. So in the example above, the numbers array has been rewritten with each value plus one. But if you wanted to keep your original numbers array, you would simply declare it to a new array like so
let numbersPlusOne = numbers.map(numb=> numb+1).
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The main difference here, is that whatever condition you pass, will give you a mutated array of all the items that meet that condition.
let numbers = [1,2,3,4,5] numbers = numbers.filter(numb=> numb % 2 == 0) console.log(numbers) // will be [2,4]
Whatever condition you pass will be checked for each item in the array and it will be added to the new array and returned.
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
This one is just a bit more complicated, because there are more arguments. But in its simplest form you can take an array and perform the same function on each element to receive back a single value. Back to our numbers array
let numbers = [1,2,3,4,5] numbers.reduce( (accumulator, currentValue) => accumulator + currentValue ) console.log(numbers) // 15
Keep in mind the computation you do will be done on each item in the array, and the
accumulator is the running total. There are also optional arguments of
array that follow the
currentValue (before the arrow function) but I won't get into those here.
Hope this helps!