Swift 3 Array, remove more than one item at once, with .remove(at: i)

swift 4 remove object from array
swift array remove object
swift 4.2 remove object from array
swift remove custom object from array
swift array remove indexset
swift array, remove range
remove item from array swift4
swift array filter and remove

Is it possible to remove more than one item from an array, at the same time, using index locations as per .remove(at: i) kind of like:

Pseudo code:

myArray.remove(at: 3, 5, 8, 12)

And if so, what's the syntax for doing this?


UPDATE:

I was trying this, it worked, but the extension in the answer below is much more readable, and sensible, and achieves the goal of one that's exactly as the pseudo code.

an array of "positions" is created: [3, 5, 8, 12]

let sorted = positions.sorted(by: { $1 < $0 })
for index in sorted
{
    myArray.remove(at: index)
}

It's possible if the indexes are continuous using removeSubrange method. For example, if you would like to remove items at index 3 to 5:

myArray.removeSubrange(ClosedRange(uncheckedBounds: (lower: 3, upper: 5)))

For non-continuous indexes, I would recommend remove items with larger index to smaller one. There is no benefit I could think of of removing items "at the same time" in one-liner except the code could be shorter. You can do so with an extension method:

extension Array {
  mutating func remove(at indexes: [Int]) {
    for index in indexes.sorted(by: >) {
      remove(at: index)
    }
  }
}

Then:

myArray.remove(at: [3, 5, 8, 12])

UPDATE: using the solution above, you would need to ensure the indexes array does not contain duplicated indexes. Or you can avoid the duplicates as below:

extension Array {
    mutating func remove(at indexes: [Int]) {
        var lastIndex: Int? = nil
        for index in indexes.sorted(by: >) {
            guard lastIndex != index else {
                continue
            }
            remove(at: index)
            lastIndex = index
        }
    }
}


var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
myArray.remove(at: [5, 3, 5, 12]) // duplicated index 5
// result: [0, 1, 2, 4, 6, 7, 8, 9, 10, 11, 13] only 3 elements are removed

ios, It's possible if the indexes are continuous using removeSubrange method. For example, if you would like to remove items at index 3 to 5: myArray. Specifically, you use the Array type to hold elements of a single type, the array’s Element type. An array can store any kind of elements—from integers to strings to classes. Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets.


Remove elements using indexes of an array elements:

  1. Array of Strings and indexes

    let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
    let indexAnimals = [0, 3, 4]
    let arrayRemainingAnimals = animals
        .enumerated()
        .filter { !indexAnimals.contains($0.offset) }
        .map { $0.element }
    
    print(arrayRemainingAnimals)
    
    //result - ["dogs", "chimps", "cow"]
    
  2. Array of Integers and indexes

    var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    let indexesToRemove = [3, 5, 8, 12]
    
    numbers = numbers
        .enumerated()
        .filter { !indexesToRemove.contains($0.offset) }
        .map { $0.element }
    
    print(numbers)
    
    //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
    

Remove elements using element value of another array

  1. Arrays of integers

    var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    let elementsTobeRemoved = [3, 5, 8, 12]
    let arrayResult = numbers.filter { element in
        return !elementsTobeRemoved.contains(element)
    }
    print(arrayResult)
    
    //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
    
  2. Arrays of strings

    let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
    let arrayRemoveLetters = ["a", "e", "g", "h"]
    let arrayRemainingLetters = arrayLetters.filter {
        !arrayRemoveLetters.contains($0)
    }
    
    print(arrayRemainingLetters)
    
    //result - ["b", "c", "d", "f", "i"]
    

How to remove multiple items from a swift array?, Given your array var numbers = [1, 2, 3, 4]. and a Set of indexes you want to remove let indexesToRemove: Set = [1, 3]. You want to remove the  Thanks to Apache Commons Utils, You can use there ArrayUtils class to remove an element from array more easily than by doing it yourself. One thing to remember is that Arrays are fixed size in Java, once you create an array you can not change their size, which means removing or deleting an item doesn't reduce the size of the array.


Swift 4

extension Array {

    mutating func remove(at indexs: [Int]) {
        guard !isEmpty else { return }
        let newIndexs = Set(indexs).sorted(by: >)
        newIndexs.forEach {
            guard $0 < count, $0 >= 0 else { return }
            remove(at: $0)  
        }
    }

}

var arr = ["a", "b", "c", "d", "e", "f"]

arr.remove(at: [2, 3, 1, 4])

result: ["a", "f"]

Remove multiple indices from array, Note that PermutationGenerator is going away in Swift 3 and also doesn't keep the ordering the same, though perhaps it did at one time. Using the accepted  Thanks to Kristian Sletten for pointing out the issue with the loop skipping the following item. Using the Array filter Method to Remove Items By Value. Unlike the splice method, filter creates a new array. filter() does not mutate the array on which it is called, but returns a new array. filter() has a single parameter, a callback method.


Removing elements at more than one index from an array?, var a = ["a", "b", "c", "d"] let b = a.remove(elementsAtIndices: [3, 1]) print(a) look at: https://github.com/apple/swift/blob/master/test/Prototypes/Algorithms.swift endIndex) // Remove the extra elements from the end of the array. self. rather than a Sequence because we need to iterate through it twice (once  Deleting multiple items from a list is not directly possible in one command in Python. There are a few approaches to accomplishing something like it. Which one is best depends on your objective. One problem is when you delete an item, the indices of every item after it also changes.


You can make a set of indexes you want to remove.

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let indexSet = [3, 5, 8, 12]
indexSet.reversed().forEach{ array.remove(at: $0) }
print(array)

Output: [0, 1, 2, 4, 6, 7, 9, 10, 11]

In case indexes are continuous then use removeSubrange

array.removeSubrange(1...3) /// Will remove the elements from 1, 2 and 3 positions.

removeObjectsAtIndexes:, This method is similar to removeObjectAtIndex: , but allows you to efficiently remove multiple objects with a single operation. indexes specifies the locations of​  Varun May 8, 2018 Python : How to remove multiple elements from list ? In this article we will discuss different ways to remove multiple elements from list. Suppose we have a list of numbers i.e. Now we want to remove all the numbers from list, which are multiple of 3. Iterate over the list and remove them one by one if its divisible by 3 i.e.


removeSubrange(_:), All the elements following the specified position are moved to close the gap. This example removes three elements from the middle of an array of measurements. The JavaScript method toString () converts an array to a string of (comma separated) array values. The join () method also joins all array elements into a string. It behaves just like toString (), but in addition you can specify the separator: When you work with arrays, it is easy to remove elements and add new elements.


Remove all instances of an object from an array, Arrays already have methods to find and remove a single item, or remove all items at once, but for removing all instances of a specific item you need to var numbers = [2, 1, 2, 3, 2, 4, 2, 5] Explore the docs to learn more. Element in an array are indexed from 0 to the number of elements minus one. So an array with 3 elements will have elements at index 0, 1 and 2. To remove an item


How to remove duplicate items from an array, There are several ways of removing duplicate items from an array, but one of the easiest is with the following extension on Array : extension Array where Element: let numbers = [1, 5, 3, 4, 5, 1, 3] let unique = numbers.removingDuplicates() Explore the docs to learn more · Sponsor Hacking with Swift and  Swift’s array, set, and dictionary types are implemented as generic collections. For more about generic types and collections, see Generics. Mutability of Collections. If you create an array, a set, or a dictionary, and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the