Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if all items in an array are identical?

Tags:

arrays

ruby

People also ask

How can you tell if an array is identical?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you check all values of an array are equal or not in Javascript?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.


You can use Enumerable#all? which returns true if the given block returns true for all the elements in the collection.

array.all? {|x| x == array[0]}

(If the array is empty, the block is never called, so doing array[0] is safe.)


class Array
  def same_values?
    self.uniq.length == 1
  end
end


[1, 1, 1, 1].same_values?
[1, 2, 3, 4].same_values?

What about this one? It returns false for an empty array though, you can change it to <= 1 and it will return true in that case. Depending on what you need.


I too like preferred answer best, short and sweet. If all elements were from the same Enumerable class, such as Numeric or String, one could use

def all_equal?(array) array.max == array.min end

I would use:

array = ["rabbits","rabbits","hares", nil, nil]
array.uniq.compact.length == 1

I used to use:

array.reduce { |x,y| x == y ? x : nil }

It may fail when array contains nil.