Created
November 13, 2016 16:50
-
-
Save bhuizi/82aae843794e08eedb2419d29bf89ef4 to your computer and use it in GitHub Desktop.
array 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
basic example | |
var data = [30, 5], | |
initialValue = 0; | |
reducer = function(accumulator, initialValue){ | |
return accumulator + initialValue; | |
} | |
var newData = data.reduce(reducer, initialValue); | |
console.log('new data is', newData); | |
var votes = [ | |
'react', | |
'angular', | |
'angular', | |
'react', | |
'react', | |
'ember', | |
'vanilla' | |
], | |
initialValue = {}, | |
reducer = function(tally, vote){ | |
if(!tally[vote]) { | |
tally[vote] = 1; | |
} else { | |
tally[vote] = tally[vote] + 1; | |
} | |
return tally; | |
} | |
result = votes.reduce(reducer, initialValue); | |
console.log('finally totals are', result); | |
var data = [1, 2, 3, 4, 5]; | |
var double = data.reduce(function(acc, value){ | |
acc.push(value * 2); | |
return acc; | |
}, []); | |
console.log(double); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment