Skip to content

Instantly share code, notes, and snippets.

@usmaanalii
Created July 26, 2017 08:00
Show Gist options
  • Save usmaanalii/39eb3f21f4521b2a78bec2fe24cc4469 to your computer and use it in GitHub Desktop.
Save usmaanalii/39eb3f21f4521b2a78bec2fe24cc4469 to your computer and use it in GitHub Desktop.

4. Array Cardio Day 1

What I learned on this mini-project.

filter

This can be used to assess each item of an array against a condition, and create a new one for those that pass.

https://gist.github.com/47d6939c07d45a1af98d8585228a01a4

Here, we used a more concise syntax. If the resulting boolean expression returns true it will 'pass the condition' and be returned in the filtered array.

  • inventor takes the role of the current iterand, much like i in a traditional for (var i = 0; i++; i < arr.length) loop

Array.from

This is useful when you wish to apply array methods to a node list extracted from a website (in this case wikipedia).

https://gist.github.com/930f59b9e1695b4ec046dfea67b8efe1

Now, you are able to apply, map, reduce, sort etc... to links.

reduce

This method takes an array and attempts to whittle it down to single value (or values shown in the next exanple).

https://gist.github.com/dd72374a1b86c5b0508f39bfa28dca4e

It's best to think of the parameters total and inventor as an accumulator and iterand. The 0 provides a starting point for the total, since if it were ommited, it would use undefined to add the first iterand to.

reduce (part 2)

Perhaps a more complex use case for reduce is when trying to reduce multiple elements in an array.

The goal was to reduce each element to the number of occurrences in the array.

https://gist.github.com/d65be6809c921e5ef30a15ecd429ffbb

The key in this case, was to use an empty object as the initial value for the object, and call obj[key] for each iteration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment