Jump to content

Array comparison


Lpsd

Recommended Posts

  • Administrators

Let's say I have two arrays

a = { "apple", "pear", "orange", "pineapple", "tomato" }
b = { "kiwi", "strawberry", "melon" }

How can I compare the two arrays, and detect the entries in array b which aren't in array a?

Edited by LopSided_
Link to comment

I don't think there's a native LUA or MTA function for that, but something like this should work

local a = { "apple", "pear", "orange", "pineapple", "tomato" }
local b = { "kiwi", "strawberry", "melon", "apple", "tomato" }

function checkDuplicate(arr1, arr2)
	local duplicateEntries = {}
	for i = 1, #arr1 do
        local found = false
		for k = 1, #arr2 do
			if arr1[i] == arr2[k] then
				found = true
			end
		end
        if not found then
            table.insert(duplicateEntries, arr1[i])
        end
	end
	return duplicateEntries
end
    
local doubleEntries = checkDuplicate( a, b )
    
local strEntries = table.concat(doubleEntries, ",")
   
print(strEntries)

 

Link to comment
  • Administrators
1 hour ago, pa3ck said:

I don't think there's a native LUA or MTA function for that, but something like this should work


local a = { "apple", "pear", "orange", "pineapple", "tomato" }
local b = { "kiwi", "strawberry", "melon", "apple", "tomato" }

function checkDuplicate(arr1, arr2)
	local duplicateEntries = {}
	for i = 1, #arr1 do
        local found = false
		for k = 1, #arr2 do
			if arr1[i] == arr2[k] then
				found = true
			end
		end
        if not found then
            table.insert(duplicateEntries, arr1[i])
        end
	end
	return duplicateEntries
end
    
local doubleEntries = checkDuplicate( a, b )
    
local strEntries = table.concat(doubleEntries, ",")
   
print(strEntries)

 

Works great as expected, thanks a bunch ^_^

Link to comment

I know the code pa3ck it's working, but once the element is found on the second array it's useless continue the loop, except if you want to count the number of elements in arr2 equals to an element in arr1, but the function is not made and still will not work in this case. So isn't it better to insert a "break" between line 11 and 12?

Have a nice day :) 

  • Like 1
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...