Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created July 10, 2017 19:27
Show Gist options
  • Save prof3ssorSt3v3/01b880467abc7e0ac2d02bfdfba6e1e6 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/01b880467abc7e0ac2d02bfdfba6e1e6 to your computer and use it in GitHub Desktop.
//Array reduce method
//reduce all the values in an array into a single result
// Uses a callback function just like map, forEach, filter, etc
// array.reduce(callback, initialValue)
// also has a second parameter which is an initialValue
let numbers = [12, 34, 56, 78, 91];
//find the sum of all the numbers
let movies = ['Layer Cake', 'Star Wars', 'Star Trek', 'Jaws', 'Jurassic Park', 'Gross Pointe Blank', 'Eternal Sunshine of the Spotless Mind', 'Memento', 'Dog Soldiers', 'The Host', 'Gran Torino', 'Close Encounters of the Third Kind', 'Good Will Hunting', 'Casino Royale', 'Almost Famous'];
//find the first movie alphabetically
let sum = numbers.reduce(function(passedIn, item){
//console.log(passedIn, item);
return passedIn + item;
}, 0);
console.log('Total is', sum, '\n');
let first = movies.reduce(function(current, item){
console.log('comparing', current, 'to', item);
return (current < item) ? current: item;
}, "\u0434");
console.log('First movie is', first);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment