map
=> Takes an array, and then applies a function to every element of that array.filter
=> Takes an array, and passes every element through a function. It only keeps the element if the function returnstrue
.sort
=> By default, it sorts the elements of an array in alphabetical order. But, if you give it a function, it will use it to sort the array in the following way:- The function takes two arguments to compare,
a
andb
. - The function returns a negative number if
a
is lower thanb
. - The function returns zero if
a
has the same value asb
. - The function returns a positive number is
a
is higher thanb
.
- The function takes two arguments to compare,
reduce
=> Starts with an accumulator. It starts with the first element of the array. Then it goes through the rest of the elements, and for each one, it applies a function to the accumulator and the element and puts the result back into the accumulator. The function returns what the accumulator is at the end.
- Let's say you have
[1, 2, 4, 6].map(x => x*2)
. It applies the doubling function to every element of the array, so it returns[2, 4, 8, 12]
. - Let's say you have
["a", "hello", "b", "goodbye"]
and you want to filter out all single-letter strings. You can call filter with the following function:x => x.length > 1
. That will only returntrue
if the string has more than one letter. - You want to sum all the elements of
[6, 5, 3, 1, 8, 7, 2, 4]
. You can call reduce with this function:(acc, val) => acc + val
:- It starts with an accumulator value of
6
, the first value of the array. - It goes to the next element,
5
, and applies the function to6
and it. It adds 6 + 5 = 11. That's the new accumulator value. - It goes to the next element,
3
, and applies the function to11
and it. It adds 11 + 3 = 14. That's the new accumulator value. - It goes to the next element,
1
, and applies the function to14
and it. It adds 14 + 1 = 15. That's the new accumulator value. - And so on, until we get to the accumulator value of
36
. That's the answer. - This method works because this is just a convoluted way of just adding on every element of the array one by one.
- It starts with an accumulator value of
- You have
[9, 4, 5, 3, 1].sort((a, b) => a - b)
. The function returns a negative number if a < b, and a positive number if a > b. So it will sort it from lowest to highest:[1, 3, 4, 5, 9]
. - You have
[9, 4, 5, 3, 1].sort((a, b) => b - a)
. The function returns a negative number if a > b, and a positive number if a < b. So it will sort it from highest to lowest:[9, 5, 4, 3, 1]
.