Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript removes the same elements from the array


May 09, 2021 CoffeeScript


Table of contents


Remove the same elements from the array

Problem

You want to remove the same element from the array.

Solution

Array::unique = ->
  output = {}
  output[@[key]] = @[key] for key in [0...@length]
  value for key, value of output

[1,1,2,2,2,3,4,5,6,6,6,"a","a","b","d","b","c"].unique()
# => [ 1, 2, 3, 4, 5, 6, 'a', 'b', 'd', 'c' ]

Discuss

There are many unique ways to do this in JavaScript. This time it's based on "the fastest way to find the only element of an array" from here.

Note: Extending a local object is generally considered a bad practice in JavaScript, even though it is fairly common in ruby languages (Reference: Maintainable JavaScript: Don't modify objects you don't't own.)