Many Copies of Filtered Array

So I have an array of items, we’ll make it Strings for the example but they’re actually custom objects:

let original = ["apple1", "apple2", "banana1", "banana2", "carrot1", "carrot2", "donut1", "donut2"]

and then I filter the array to only get the “1” foods:

let filtered = original.filter { $0.contains("1") }

Then I want to get a random element from my filtered array and remove it when I do:

let randomIndex = filtered.getRandomIndex // returns a random index in the array
let randomElement = filtered[randomIndex]
filtered.remove(at: randomIndex)

Then when the filtered array contains no more data, I want to reset it back to its original state.

Option 1 is to create three arrays and reset the filtered array when it’s empty:

// original - all strings
// filtered - filtered strings
// ogFiltered - original set of filtered strings

if filtered.count == 0 {
    filtered = ogFiltered
}

Option 2 is to refilter the original array when filtered is empty:

if filtered.count == 0 {
    filtered = original.filter { $0.contains("1") }
}

So my question is, which is the better way to do this? Is it better/worse to have more arrays or more computations? Thanks!

More computations and less use of memory, unless it’s too slow.
If it was a huge list with 100,000 items, and you filter it down to 19, I would hang on to that. If you filter it down to 99,000, I would not hang on to that.
If the source might have have changed, I would re-filter it every time, unless you want it to be the same filtered result every time, then I would hang on to it.
It depends. :slight_smile:

1 Like

Thanks @sgerrard!

The filtered array is around the same size as the original array, so I will refilter each time. And the computation time seems pretty quick, since the object contains only string properties.

Thanks for your insight!

This topic was automatically closed after 166 days. New replies are no longer allowed.