2

How can I find unique values in an array.

For instance:

my_array = [2,4,4,5,5,7]

In the above array are two unique values 2 and 7 and I would like to know either a self defined or other method to assign these unique values to variables.

2
  • 1
    running count on the array every time will be super slow if you're working with a large array, as it grows with O(n^2) Commented Oct 31, 2017 at 22:22
  • arr.uniq.select { |n| arr.count(n) == 1 } would be an improvement to my earlier suggestion, though still not as performant as the answers given so far. Commented Oct 31, 2017 at 23:03

2 Answers 2

3

Use array.group_by.

my_array.group_by{|v| v}.delete_if{|k,v| v.length > 1}.keys

or alternatively

  my_array.group_by{|v| v}.select{|k,v| v.length == 1}.keys
Sign up to request clarification or add additional context in comments.

3 Comments

not sure why this is being downvoted. I just benchmarked it with a 2 million element array and it seems relatively performant, and correct.
Have you got the benchmark results? It would be good to be able to compare all the methods.
I just generated an array in irb with 2 million elements, called shuffle, then called Benchmark.measure. The each with object measure was about 1.14s real time vs group_by at 1.66s
2

This is a bit leggy, perhaps, but gets the job done

my_array.each_with_object(Hash.new(0)){|x,h| h[x] += 1}.select{|k,v| v == 1}.keys

4 Comments

This returns an array with the unique values of the original array. Is it in terms of result in anyway different to or better then myarray.select { |n| myarray.count(n) == 1 }? I'm assuming it might be faster?
much faster. myarray.count will hang on huge shuffled arrays.
which of these two answers is faster and better practice?
Id say Davids is slightly faster, but mine is a bit more readable. If you need performance, go with davids, readability, mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.