Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element of a given value from an array in Swift

Tags:

swift

I want to remove all elements of value x from an array that contains x, y and z elements

let arr = ['a', 'b', 'c', 'b'] 

How can I remove all elements of value 'b' from arr?

like image 791
Encore PTL Avatar asked Jun 07 '14 01:06

Encore PTL


People also ask

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove an item from an array by value?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

How do you remove an element from value?

We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.


2 Answers

A filter:

 let farray = arr.filter {$0 != "b"}  
like image 110
iluvcapra Avatar answered Oct 08 '22 08:10

iluvcapra


var array : [String] array = ["one","two","one"]  let itemToRemove = "one"  while array.contains(itemToRemove) {     if let itemToRemoveIndex = array.index(of: itemToRemove) {         array.remove(at: itemToRemoveIndex)     } }  print(array) 

Works on Swift 3.0.

like image 20
Nitrousjp Avatar answered Oct 08 '22 09:10

Nitrousjp