How to check for duplicates while pushing to array?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Bluscream
Posts: 16
Joined: 10 Jan 2017, 23:12
Contact:

How to check for duplicates while pushing to array?

Post by Bluscream » 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: 1648
Joined: 06 Oct 2015, 21:39

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

Post by kczx3 » 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: 1468
Joined: 18 Apr 2014, 19:05
Contact:

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

Post by Chunjee » 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?

Post by Crehose » 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.
Post Reply

Return to “Ask for Help (v1)”