WishIHadThreeGuns
WishIHadThreeGuns

Reputation: 1469

Remove elements from Array of Array Swift

For context I'm creating my own hashmap in swift.

I've got an element and I'm storing the elements in buckets which is an array of arrays

struct Element {
    var key: Int
    var value: Int
}

class MyHashMap {
    var buckets : [[Element]] = [[]]

    init() {
        buckets = [Array(repeating: Element(key: -1, value: -1), count: 2)]
        buckets.append([Element(key: 3, value: 4)])
    }

}

I want to remove all the buckets where the key is -1 and I'm struggling.

Flatmap does not return the right type i.e.

hashmap.buckets.flatMap{$0}.filter{$0.key != -1}

is incorrect.

How can I remove all of the buckets with key -1?

Upvotes: 0

Views: 1060

Answers (2)

Martin R
Martin R

Reputation: 539685

Map the outer array to a new array of arrays, where from the inner array only the elements with key != -1 are preserved. I would make this a method of the MyHashMap class:

class MyHashMap {
    // ...

    func compactBuckets() {
        buckets = buckets.map { $0.filter { $0.key != -1 }}
    }
}

Alternatively (and possibly more efficient), with a loop over the indices of the outer array:

    func compactBuckets() {
        for i in buckets.indices {
            buckets[i].removeAll(where: { $0.key == -1 })
        }
    }

In either case you may additionally want to remove empty inner arrays from the outer array:

        buckets.removeAll(where: { $0.isEmpty })

Upvotes: 1

Joakim Danielson
Joakim Danielson

Reputation: 51882

You can use removeAll where you filter with contains for the buckets

hashmap.buckets.removeAll { $0.contains { $0.key == -1 } }

Upvotes: 0

Related Questions