Page 1 of 1
How to check if all values in an Array are equal?
Posted: 26 Jun 2022, 05:36
by KilliK
Hello.
How can I check if all the values in an Array are equal or not? and when they are equal, to get their identical value?
for example
they are all equal with the same value A
Array:=["A","A","A","A","A"]
they are not all equal:
Array:=["A","A","B","A","A"]
what is the simplest method to achieve this?
Re: How to check if all values in an Array are equal? Topic is solved
Posted: 26 Jun 2022, 06:42
by mikeyww
Code: Select all
For arrNum, arr in [["A","A","A","A","A"], ["A","A","B","A","A"], ["", "C"], ["", ""], ["L"]] {
test := same(arr)
MsgBox, 64, Result #%arrNum%, % "Same: " (test.equal ? "True" : "False") "`n`nValue: " test.value
}
same(arr) {
For itemNum, item in arr
If (itemNum = 1 || item = value)
value := item
Else Return {value: "", equal: False}
Return {value: value, equal: True}
}
Re: How to check if all values in an Array are equal?
Posted: 26 Jun 2022, 06:46
by Helgef
If array values are numeric,
min(a*) == max(a*)
Cheers
Edit, alternative, case sensitive,
Code: Select all
same(arr) {
v1 := arr[1]
for k, v in arr
if !(v1==v)
return false
return true
}
Re: How to check if all values in an Array are equal?
Posted: 26 Jun 2022, 09:32
by KilliK
thank you very much for all your help.
Re: How to check if all values in an Array are equal?
Posted: 26 Jun 2022, 10:12
by Chunjee
https://biga-ahk.github.io/biga.ahk/#/?id=isequal approach
Code: Select all
A := new biga() ; requires https://biga-ahk.github.io/biga.ahk
arr1 := ["A","A","A","A","A"]
arr2 := ["A","A","B","A","B"]
msgbox, % A.isEqual(arr1*)
; => true
msgbox, % A.isEqual(arr2*)
; => false
One other benefit is it works with objects too:
Code: Select all
obj1 := {"name": "Zues"}
obj2 := {"name": "Jupiter"}
msgbox, % A.isEqual(obj1, obj2)
; => false
Re: How to check if all values in an Array are equal?
Posted: 26 Jun 2022, 13:45
by flyingDman
Or:
Code: Select all
For arrNum, arr in [["A","A","A","A","A"], ["A","A","B","A","A"], ["", "C"], ["", ""], ["L"]]
msgbox % same(arr)
same(array)
{
arr0 := []
for x,y in array
arr0[y] := !ObjHasKey(arr0, y) ? 1 : arr0[y] + 1
return arr0.count() = 1 ? "True" : "False"
}
Re: How to check if all values in an Array are equal?
Posted: 26 Jun 2022, 13:58
by mikeyww
All good. When the returned value is true (i.e., elements are the same), then the value will be the value of the first array element (or any of them).
Re: How to check if all values in an Array are equal?
Posted: 27 Jun 2022, 18:33
by Chunjee
oh dear