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?
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.
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.
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.
A filter:
let farray = arr.filter {$0 != "b"}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With