In PHP it's one line of code:
$array_without_empty_strs = array_filter($array_with_empty_strs);
What's the objective C equivalent?
UPDATE - Added the following test code to illustrate the use of Nikolai Ruhe's solution:
// SOLUTION Test Code
NSMutableArray *myArray = [[NSMutableArray alloc] init ];
[myArray addObject:[NSNumber numberWithInt:5]];
[myArray addObject:@""];
[myArray addObject:@"test"];
NSLog(@"%@", myArray);
[myArray removeObject:@""];
NSLog(@"%@", myArray);
// SOLUTION Test Code Output
2012-07-12 08:18:16.271 Calculator[1527:f803] (
5,
"",
test
)
2012-07-12 08:18:16.273 Calculator[1527:f803] (
5,
test
)
To remove the empty strings from an array, we can use the filter() method in JavaScript. In the above code, we have passed the callback function e => e to the filter method, so that it only keeps the elements which return true . empty "" string is falsy value, so it removes from the array.
NSArray is not editable, so that you cannot modify it. You can copy that array to NSMutableArray and remove objects from it. And finally reassign the values of the NSMutableArray to your NSArray.
In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).
It's even more simple:
[mutableArrayOfStrings removeObject:@""];
If your array is not mutable you have to create a mutableCopy
before.
removeObject:
removes all objects from an array that return YES from isEqual:
.
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