How to check for duplicates while pushing to array?

Get help with using AutoHotkey and its commands and hotkeys
Bluscream
Posts: 15
Joined: 10 Jan 2017, 23:12
GitHub: Bluscream

How to check for duplicates while pushing to array?

12 Aug 2020, 20:38

How do i do this? Preferably as base extension

Code: Select all

array := [1,2,3]
array.PushSingle(2)
; array is still [1,2,3]
array.PushSingle(4)
; array is [1,2,3,4]
User avatar
kczx3
Posts: 1223
Joined: 06 Oct 2015, 21:39

Re: How to check for duplicates while pushing to array?

12 Aug 2020, 21:00

Use an object instead otherwise you have to loop over the entire array every time you want to push a unique value to it.
User avatar
Chunjee
Posts: 741
Joined: 18 Apr 2014, 19:05
GitHub: Chunjee

Re: How to check for duplicates while pushing to array?

12 Aug 2020, 21:02

I like .indexOf but ahk doesn't come with it by default

Code: Select all

; requires https://www.npmjs.com/package/array.ahk

array := [1,2,3]
value := 2

if (array.indexOf(value) = -1) {
   array.push(value)
}
; => [1,2,3]

However, to answer the question you can do this to modify the base array object and add that method.

Code: Select all

; redefine Array() to add custom _Array base object
Array(prms*) {
	prms.base := _Array
	return prms
}


array := [1,2,3]
value := 2

array.singlePush(2)
; => [1,2,3]
msgbox, % array.Count()
; => 3


; Define the base class.
class _Array {

	singlePush(param_value) {
		if (this.indexOf(param_value) = -1) {
			this.Push("" param_value)
		}
	}

	indexOf(searchElement, fromIndex:=0) {
		
		len := this.Count()

		if (fromIndex > 0)
			start := fromIndex - 1    ; Include starting index going forward
		else if (fromIndex < 0)
			start := len + fromIndex  ; Count backwards from end
		else
			start := fromIndex


		loop, % len - start
			if (this[start + A_Index] = searchElement)
				return start + A_Index

		return -1
	}
}
Crehose
Posts: 6
Joined: 08 Aug 2020, 19:46

Re: How to check for duplicates while pushing to array?

12 Aug 2020, 21:38

You can use a loop to iterate over the array and check for the duplicate elements when you add new values or you can use an object.

Return to “Ask For Help”

Who is online

Users browsing this forum: Aggronaught, elvo11, Google [Bot], JoeWinograd, keylo, mikeyww, TAC109 and 52 guests