Reduce with strings
by Matthew Day
JavaScript
/*
Source: https://egghead.io/lessons/javascript-introducing-reduce-transforming-arrays-functionally
*/
var data = ['a', 'b', '1', '2', '3'];
var reducer = function(accumulator, item, index) {
if(index >= 2) {
return accumulator + Number(item);
}
else {
return 0;
}
}
var initialValue = 0;
var total = data.reduce(reducer, initialValue);
console.log("The sum is", total);
/*
// Source: Helping a Thinkful student who was getting an error because the else block was left out
const doneIt = ['hello','bunny','1','2','3','4'];
const newSum = doneIt.reduce((sum, value, index) => {
if(index >= 2) {
return sum + Number(value);
} else {
return 0;
}
}, 0);
console.log(newSum);
*/