Array method that combines 'uniq' and 'compact'

webster

I am trying to find unique elements in an array and remove the nil values from it. My solution looks like this:

@array = [1, 2, 1, 1, 2, 3, 4, nil, 5, nil, 5] 
@array.uniq.compact # => [1, 2, 3, 4, 5] 

Is there any single method that does both the operations? If not, which is efficient, @array.uniq.compact or @array.compact.uniq?

SHS

No, but you can append them in any order you like i.e.

array.uniq.compact
array.compact.uniq

As pointed out by phts, you can pass a block to uniq but I don't see that being a very helpful alternative over uniq.compact.

For better speed however, something like the following might help:

[].tap do |new_array|
  hash = {}
  original_array.each do |element|
    next if element.nil? || !hash[element].nil?
    new_array << (hash[element] = element)
  end
end

Finally, if speed isn't an issue and you'll be frequently using this method, then you could create your own method:

class Array
  def compact_uniq
    self.compact.uniq
  end

  def compact_blank # in case you want to remove all 'blanks' as well
    self.compact.reject(&:blank?)
  end
end

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Ruby and the uniq method

From Dev

Uniq array by key ruby

From Dev

Bash - sort and uniq on array

From Dev

rails compact array and NilClass

From Dev

rails compact array and NilClass

From Dev

reduce combines an array into a single value

From Dev

Source code for uniq method in Ruby

From Dev

counting uniq values in array not working

From Dev

PHP Array permutation uniq ordered

From Dev

Finding `uniq` values in array with their indexes

From Dev

Is there an RX method which combines map and filter?

From Dev

flatten and compact an array more efficiently

From Dev

Javascript Unnecessarily Compact Array Operations

From Dev

Data type that combines properties of array and dictionary

From Dev

Rails - Using .uniq on an array inside a multidimensional array

From Dev

Rails UNIQ method not working - Rails 4

From Dev

Compact syntax for static Create() method on generic class?

From Dev

Rails NoMethodError: undefined method `compact' error

From Dev

Compact syntax for static Create() method on generic class?

From Dev

How Create array with uniq key using php

From Dev

Get uniq elements from array of objects

From Dev

Uniq an array by one column and join another column

From Dev

PHP Compact() function returning a empty array

From Dev

compact() vs manual array declaration on PHP

From Dev

Most Compact way to Serialize an Array of Longs in Java

From Dev

How to parse a compact JSON Array in android

From Dev

PHP Compact() function returning a empty array

From Dev

Is there any way to change input method on .NET Compact Framework 2.0

From Dev

Calculate time complexity of Ruby Array#uniq own implementation

Related Related

HotTag

Archive