Created
October 13, 2021 15:48
-
-
Save ch1c0t/2802867351195a9d8741010fc1bf4593 to your computer and use it in GitHub Desktop.
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
# Returns a new Array containing only those elements that occur | |
# twice or more times in the original Array. | |
Array::recurrences = -> | |
FirstOccurrences = [] # of the recurring elements | |
# in the original Array | |
occurrences = {} # from an element to an Array of indexes | |
# where it occurs | |
for element, index in @ | |
unless occurrences.hasOwnProperty element | |
occurrences[element] = [] | |
occurrences[element].push index | |
indexes = occurrences[element] | |
if indexes.length is 2 | |
FirstOccurrences.push indexes[0] | |
FirstOccurrences | |
.sort() | |
.map (index) => | |
@[index] | |
# It preserves the order, in which elements occur for the first | |
# time in the original Array. | |
console.log [1, 1, 2, 3, 4, 5, 5, 2, 3, 5, 6, 7].recurrences() | |
#=> [ 1, 2, 3, 5 ] | |
# and not [ 1, 5, 2, 3 ], for example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment