# Removing elements at more than one index from an array?

**URL:** <https://forums.swift.org/t/removing-elements-at-more-than-one-index-from-an-array/19953>\
**Category:** Using Swift\
**Created:** [January 29, 2019, 7:41pm UTC](https://forums.swift.org/t/removing-elements-at-more-than-one-index-from-an-array/19953 "2019-01-29T19:41:36Z")\
**Posts on this page:** 1\
**Showing post:** 13

<div class="post-metadata">

**Author:** ![anon31136981](https://avatars.discourse-cdn.com/v4/letter/a/c2a13f/32.png) [@anon31136981](https://forums.swift.org/u/anon31136981)\
**Post date:** [January 30, 2019, 2:54pm UTC](https://forums.swift.org/t/removing-elements-at-more-than-one-index-from-an-array/19953/13 "2019-01-30T14:54:52Z")

</div>

This should be sufficient for trapping on duplicated indices, because shiftLeft() will be called with the same index twice in a row iff it was included at least twice in the array of indices to remove.

```swift
extension Array {
    mutating func remove(elementsAtIndices indicesToRemove: [Int]) -> [Element] {
        guard !indicesToRemove.isEmpty else {
            return []
        }
        
        // Copy the removed elements in the specified order.
        let removedElements = indicesToRemove.map { self[$0] }
        
        // Sort the indices to remove.
        let indicesToRemove = indicesToRemove.sorted()
        
        // Shift the elements we want to keep to the left.
        var destIndex = indicesToRemove.first!
        var srcIndex = destIndex + 1
        var prevRemovedIndex = destIndex
        func shiftLeft(untilIndex index: Int) {
            precondition(index != prevRemovedIndex)
            prevRemovedIndex = index
            while srcIndex < index {
                self[destIndex] = self[srcIndex]
                destIndex += 1
                srcIndex += 1
            }
            srcIndex += 1
        }
        for removeIndex in indicesToRemove[1...] {
            shiftLeft(untilIndex: removeIndex)
        }
        shiftLeft(untilIndex: self.endIndex)
        
        // Remove the extra elements from the end of the array.
        self.removeLast(indicesToRemove.count)
        
        return removedElements
    }
}

```

I’ll try to make it more generic.

---

_[View the full topic](https://forums.swift.org/t/removing-elements-at-more-than-one-index-from-an-array/19953)._
