Remove from the array elements that are repeated

后端 未结 5 1189
执念已碎
执念已碎 2020-12-12 01:37

What is the best way to remove from the array elements that are repeated. For example, from the array

a = [4, 3, 3, 1, 6, 6]

need to get

5条回答
  •  孤街浪徒
    2020-12-12 02:23

    Without introducing the need for a separate copy of the original array and using inject:

    [4, 3, 3, 1, 6, 6].inject({}) {|s,v| s[v] ? s.merge({v=>s[v]+1}) : s.merge({v=>1})}.select {|k,v| k if v==1}.keys
     => [4, 1] 
    

提交回复
热议问题