0

I have an array with quite a lot of elements in it. I want to remove an element by the value rather than by the key. It seems you have to do this:

array = array.filter() { $0 !== value }

For me coming from a Lua background, this seems somewhat equivalent to this Lua code:

for k,v in pairs(array) do
    if v == value then table.remove(array, k) end
end

This is a slow method, and a faster way in Lua is to set the key as the value:

array = {[value] = "something"}
array[value] = nil

Is there any equivalent to this in Swift? In my mind, a filter checks through every element, so I feel like there must be a faster way. If you use a dictionary, is it any better?

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
MysteryPancake
  • 1,365
  • 1
  • 18
  • 47
  • Related: [Array extension to remove object by value](https://stackoverflow.com/questions/24938948/array-extension-to-remove-object-by-value). – Martin R Jun 20 '17 at 06:00
  • To find the best data structure to use, we need some more info. Is the order of the array elements important? Are there any duplicate elements? How many elements do you have in the array, roughly? And are your array elements [hashable](https://developer.apple.com/documentation/swift/hashable) (i.e. can they be used as keys to Swift dictionaries)? And also, how is the array created? Are you constructing it yourself, or just getting it fully formed from somewhere else? – Jack Taylor Jun 21 '17 at 02:05
  • It contains all the nodes in an SKScene. It doesn't matter the order, and the element count varies as nodes get deleted and filtered from the array. – MysteryPancake Jun 21 '17 at 04:42

1 Answers1

0

I think the filter is the way to go for you. You could also remove the element by index but I would still go with the filter method:

Filter:

array = array.filter() { $0 !== value }

Remove by index:

if let index = array.index(where: { $0 == value }) {
    array.remove(at: index)
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • Is this a fast method though? Is there any possible way to make it faster? – MysteryPancake Jun 20 '17 at 05:44
  • 1
    @MysteryPancake, it´s fast enough. I use `filter` on larger arrays and I don´t have any issues with the prestanda nor with the `index` example. – Rashwan L Jun 20 '17 at 05:47
  • 1
    Whether filter is fast enough will depend on how many items you have in the array, and how fast it needs to be. Logically, filtering an array takes O(n) time, as you need to iterate through all the values and test each one. However, I'm not sure of the exact details of how it works in Swift; the memory management may make it more expensive. Using a dictionary will take O(1) time in most cases, although apparently the worst-case scenario for removing elements from dictionaries in Swift is O(n(log n)). – Jack Taylor Jun 21 '17 at 03:00