Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all items in a slice are equal

Tags:

equality

slice

go

I need to create a function that:

returns true if all elements in a slice are equal (they will all be the same type)
returns false if any elements in a slice are different

The only way I can think of doing it is to reverse the slice, and compare the slice and the reversed slice.

Is there a better way to do this thats good syntax and more efficient?

like image 796
XXX Avatar asked Mar 27 '16 22:03

XXX


People also ask

Is it possible to check if the slices are equal with == operator or not?

Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal. Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator. A very useful answer.

How can I check if two slices are equal?

To check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop. You can also use the reflect. DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level.

How do you check if a slice contains an element in Go?

How to check if a slice contains an element. To check if a particular element is present in a slice object, we need to perform the following steps: Use a for loop to iterate over each element in the slice . Use the equality operator ( == ) to check if the current element matches the element you want to find.

How do you check if all arrays are equal?

To check if all values in an array are equal: Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.


1 Answers

I am not sure what your though process was for reversing the slice was, but that would be unnecessary. The simplest algorithm would be to check to see if all elements after the the first are equal to the first:

func allSameStrings(a []string) bool {
    for i := 1; i < len(a); i++ {
        if a[i] != a[0] {
            return false
        }
    }
    return true
}
like image 185
Tim Cooper Avatar answered Sep 29 '22 01:09

Tim Cooper