我是coffeescript的新手。请帮帮我。
如何在数组中找到重复的值?
var arr = ['manager','manager','employee','manager',
'director','employee','manager','operatives'];
在这种情况下,它应该返回['经理','员工']。
答案 0 :(得分:5)
试试这个:
findDuplicates = (array) ->
keys = {}
for value in array
keys[value] ?= 0
keys[value]++
(key for key, count of keys when count > 1)
arr = ['manager','manager','employee','manager', 'director','employee','manager','operatives']
console.log findDuplicates(arr)
答案 1 :(得分:2)
使用filter
,更轻松。
arr = ['manager','manager','employee','manager','director','employee','manager','operatives'];
filtered = arr.filter (x, i, self) ->
self.indexOf(x) == i && i != self.lastIndexOf(x)
console.log filtered # => ['manager', 'employee']