Using the .some()
langlib function of Ballerina arrays, this could be achieved as following.
public function main() {
string[] strArr = ["Anne", "Jane", "John", "Jane", "Ivan", "Jane", "Peter", "Anne"];
_ = strArr.some(function (string s) returns boolean {
int? firstIndex = strArr.indexOf(s);
int? lastIndex = strArr.lastIndexOf(s);
if (firstIndex != lastIndex) {
_ = strArr.remove(<int>lastIndex);
}
// Returning true, if the end of the array is reached.
if (firstIndex == (strArr.length() - 1)) {
return true;
}
return false;
});
io:println(strArr);
}
Since the .some()
langlib function is used to check if at least a single member in the array follows the given condition, it could be used to determine if we've reached the end of the array and prevent the Index Out of Bound Exception.
Within the function that is passed as the parameter of the .some()
langlib function, we'd be removing only the last instance of any duplicate value. When reached to the end of the array, all the duplicate values would be removed.