Skip to content

Instantly share code, notes, and snippets.

@ch1c0t
Created October 13, 2021 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ch1c0t/2802867351195a9d8741010fc1bf4593 to your computer and use it in GitHub Desktop.
Save ch1c0t/2802867351195a9d8741010fc1bf4593 to your computer and use it in GitHub Desktop.
# 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