Last active
November 21, 2016 10:13
-
-
Save gkucmierz/acdce447ba9e77d661511fe22a01f2a3 to your computer and use it in GitHub Desktop.
Group array elements
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
| function groupBy(arr, fn) { | |
| fn = fn || ((o) => o); | |
| let g = []; | |
| let v = []; | |
| for (let i = 0; i < arr.length; ++i) { | |
| let val = fn(arr[i]); | |
| let idx = g.indexOf(val); | |
| if (idx === -1) { | |
| g.push(val); | |
| v.push([arr[i]]); | |
| } else { | |
| v[idx].push(arr[i]); | |
| } | |
| } | |
| return v; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment