Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created October 12, 2013 05:43
Show Gist options
  • Select an option

  • Save CatTail/6946252 to your computer and use it in GitHub Desktop.

Select an option

Save CatTail/6946252 to your computer and use it in GitHub Desktop.
Search using Array.prototype.reduce method.
// refer to http://ariya.ofilabs.com/2013/10/searching-using-array-prototype-reduce.html?utm_source=javascriptweekly&utm_medium=email
// old story
function findLongest(entries) {
for (var i = 0, longest = ''; i < entries.length; ++i)
if (entries[i].length > longest.length) longest = entries[i];
return longest;
}
// A version which relies on reduce is a single statement:
function findLongest2(entries) {
return entries.reduce(function (longest, entry) {
return entry.length > longest.length ? entry : longest;
}, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment