Created
October 12, 2013 05:43
-
-
Save CatTail/6946252 to your computer and use it in GitHub Desktop.
Search using Array.prototype.reduce method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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