Skip to content

Instantly share code, notes, and snippets.

@simon-tiger
Created July 26, 2020 11:18
Show Gist options
  • Save simon-tiger/bb67a9d1710ebc4177e474529560bc25 to your computer and use it in GitHub Desktop.
Save simon-tiger/bb67a9d1710ebc4177e474529560bc25 to your computer and use it in GitHub Desktop.
  • 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 returns true.
  • 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 and b.
    • The function returns a negative number if a is lower than b.
    • The function returns zero if a has the same value as b.
    • The function returns a positive number is a is higher than b.
  • 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.

Examples

  • 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 return true 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 to 6 and it. It adds 6 + 5 = 11. That's the new accumulator value.
    • It goes to the next element, 3, and applies the function to 11 and it. It adds 11 + 3 = 14. That's the new accumulator value.
    • It goes to the next element, 1, and applies the function to 14 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.
  • 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].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment