Created
September 28, 2016 21:55
-
-
Save aqualad/e212513701f10f83f55ffc05cc4d3e9a to your computer and use it in GitHub Desktop.
javascript Map and Reduce examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let selector, | |
$elements, | |
testsPassed, | |
totalTestsPassed; | |
// Select the 7th <td> from every <tr>, excluding the first <tr> | |
selector = '#testresult tr:not(:first-child) td:nth-child(7)'; | |
// Get array of selected elements | |
$elements = $$ | |
? $$(selector) // Prototype selector | |
: document.getElementBySelector(selector) // Pure JS selector | |
// Map counts from $elements innerHTML to a new array | |
testsPassed = $elements.map( $el => parseInt($el.innerHTML) ); | |
// Reduce the list of numbers to their sum | |
totalTestsPassed = testsPassed.reduce((left, right) => left + right); | |
// Condensed | |
totalTestsPassed = document.getElementsBySelector('#testresult tr:not(:first-child) td:nth-child(7)') | |
.map( $el => parseInt($el.innerHTML) ) | |
.reduce((left, right) => left + right); | |
/* Using just the reduce function with consideration for left's type change after the first iteration | |
Pass 1: reduce($el[0], $el[1]) => total // [Object, Object] => Int | |
Pass 2: reduce(total, $el[2]) => total // [Int, Object] => Int | |
*/ | |
totalTestsPassed = document.getElementsBySelector('#testresult tr:not(:first-child) td:nth-child(7)') | |
.reduce( (left, right) => parseInt(left.innerHTML || left) + parseInt(right.innerHTML) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment