0

I have an array of pairs like the example below:

array = [["human KIR2DS1", 446.0], ["mouse BMP-4", 446.0], ["mouse BMP-4", 446.0], ["mTIMP2 lot DAAP01", "435a"], ["hKIR3DL3 lot DDBL01", "435a"]]

I want to remove the duplicate pairs in the array. What is the shortest method to do this?

2
  • How about using a Set instead so there's never a need to remove duplicates? Commented Mar 3, 2014 at 19:53
  • Set class is not present in 1.8.7 ? Commented Mar 3, 2014 at 22:29

2 Answers 2

3

Use Array#uniq:

array.uniq
# => [["human KIR2DS1", 446.0], ["mouse BMP-4", 446.0], ["mTIMP2 lot DAAP01", "435a"], ["hKIR3DL3 lot DDBL01", "435a"]]

or if you want to modify the original array:

array.uniq!
array # => [["human KIR2DS1", 446.0], ["mouse BMP-4", 446.0], ["mTIMP2 lot DAAP01", "435a"], ["hKIR3DL3 lot DDBL01", "435a"]]
Sign up to request clarification or add additional context in comments.

1 Comment

It compares the elements using #hash and #eql? methods, so you can use it for the basic data types and structures (int, hashes, arrays, floats, strings). If you use custom objects though, you have to define these two methods in order for the uniq to work. Refer to ruby-forum.com/topic/129677
0

also this can be used to sort out the duplicate and return a new Set of array wihtout duplicate. I use the spread operator "..."

function unique(array) {
    return [...new Set(array)];
}

Comments

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.