Skip to content

Instantly share code, notes, and snippets.

@bhuizi
Created November 13, 2016 16:50
Show Gist options
  • Save bhuizi/82aae843794e08eedb2419d29bf89ef4 to your computer and use it in GitHub Desktop.
Save bhuizi/82aae843794e08eedb2419d29bf89ef4 to your computer and use it in GitHub Desktop.
array reduce examples
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