Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple items from a swift array?

Tags:

For example i have an array

var array = [1, 2, 3, 4]

I want to remove item at index 1 then at index 3 "let it be in a for loop".

But removing the item at index 1 will move the item at index 3 to index 2, thus messing up the second removal.

Any suggestions ?

like image 804
Raffi Avatar asked Jun 23 '16 21:06

Raffi


People also ask

How do I remove multiple elements from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.

How do I remove an element from an array in swift 5?

To remove an element from the Swift Array, use array. remove(at:index) method. Remember that the index of an array starts at 0. If you want to remove ith element use the index as (i-1).

What is array reduce in Swift?

Swift version: 5.6. The reduce() method iterates over all items in array, combining them together somehow until you end up with a single value.

What is array capacity in Swift?

The capacity property returns the total number of elements present in the array without allocating any additional storage.


2 Answers

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 values "2" and "4".

Just write

numbers = numbers
    .enumerated()
    .filter { !indexesToRemove.contains($0.offset) }
    .map { $0.element }

Result

print(numbers) // [1, 3]
like image 114
Luca Angeletti Avatar answered Oct 09 '22 07:10

Luca Angeletti


It's simple. delete items from the end.

First delete 3 and after that delete 1

like image 23
Seifolahi Avatar answered Oct 09 '22 06:10

Seifolahi