Discord
Community
DARK THEME

# Delete duplicates of in 2-dimensional arrays

We have an array:

``````arr = []
``````

And we make it 2-dimensional

``````arr = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[4, 3, 5, 2],
[2, 3, 4, 5],
[1, 2, 3, 4]
]
``````

Now a question: `How to delete duplicated 'lines' from an array?`

• `Line` is second-dimensional array, lets say arr[0]: its contains 'line' => [1, 2, 3, 4], and arr[4] contains [1, 2, 3, 4].

So in result I need to get:

``````arr = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[4, 3, 5, 2],
]
``````

We can do something like: get arr[0] and check it with arr[1], arr[2], arr[3]...

And then arr[1] with arr[2], arr[3]...

And so on...

But its too slow, so lazy...

Maybe there are some other methods?

I'll try `arr.contains(arr[0])` with `arr.removeElement(arr[0])`, but some elements get lost :(

Try to create new array arr2 and put in it 'lines' from arr and then deleting them from arr:

``````arr2 = []
d = []
while arr.length > 0
d = arr[0]
arr2.push(d)
arr.removeElement(d)
end

//arr2 missed some elements
``````

Any suggestions?

1. sort the array.
2. rewrite (add) a new element to the new array, provided that the new element is different from the last element in the new array.
3. repeat step 2 for all elements of the input array.
``````printList = function( list )
print( list )
end

isEqual = function( subListA, subListB )
local test = []
test.push(true)
subListA.forEach( function( element, index )
if element != subListB[index] then
test[0] = false
//        break
end
end
)
return test[0]
end

removeDupicate = function( list )
local newList = []
if list.length>-1 then
newList.push( list[0] )
for loop = 1 to list.length - 1
if isEqual(list[loop],newList[newList.length-1])==false then
newList.push( list[ loop ])
end
end
end
return newList
end
init = function()
l = [
[1, 1, 0, 0],
[1, 2, 3, 4],
[2, 3, 4, 5],
[4, 3, 5, 2],
[2, 3, 4, 5],
[1, 2, 3, 4],
[1, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 0],
[1, 1, 1, 1]]
l.sortList()

l.forEach( printList )
local newList = removeDupicate( l )
print('Removed duplicate item')
newList.forEach( printList )
end

update = function()
end

draw = function()
end
``````

maybe this feature will come in handy Array.prototype.includes()

`Loginus`, thanks :)

Yes its works, but in my new project sorting is forbidden (since i have some SI:DI pointers in tree maker sorting kills the right result, unsorting function required, but it make program more slowly)...

So right now I have another method of tree making (will share, but it is too thin-specialized maths), but anyway thanks ;)