Skip to content

Instantly share code, notes, and snippets.

@martinandersen3d
Forked from prof3ssorSt3v3/array-reduce.js
Created December 20, 2019 20:08
Show Gist options
  • Save martinandersen3d/81a8fd4addc9b1d64c3f01a80f1e5296 to your computer and use it in GitHub Desktop.
Save martinandersen3d/81a8fd4addc9b1d64c3f01a80f1e5296 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