2

There is a string array containing a number of strings in which multiple strings resemble each other. The requirement is to remove duplicates in the array.

Input :

["Anne", "Jane", "John", "Jane", "Ivan", "Peter", "Anne"]

Output:

["Anne","Jane","John","Ivan","Peter"]

It seems no langlib function to achieve this directly. How to remove duplicate strings in an array using Ballerina?

Anupama Pathirage
  • 631
  • 2
  • 10
  • 22

2 Answers2

4

Here are two ways of removing duplicates from a string array.

Method 1: Using indexOf method of lang.array

Method 2: Using keys method of lang.map

Sample code is as follows.

import ballerina/io;

// Method 1
function getUniqueValues(string[] names) returns string[] {
    string[] uniqueNames = [];
    foreach string name in names {
        if uniqueNames.indexOf(name) is () {
            uniqueNames.push(name);
        }
    }
    return uniqueNames;
}

//Method 2
function getUniqueValuesUsingMap(string[] names) returns string[] {
    map<()> mapNames = {};
    foreach var name in names {
        mapNames[name] = ();
    }
    return mapNames.keys();
}

public function main() {
    string[] duplicatedStrings = ["Anne", "Jane", "John", "Jane", "Ivan", "Peter", "Anne"];

    //Using Method 1
    io:println(getUniqueValues(duplicatedStrings));

    //Using Method 2
    io:println(getUniqueValuesUsingMap(duplicatedStrings));

}
Anupama Pathirage
  • 631
  • 2
  • 10
  • 22
2

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.

Anjana
  • 462
  • 2
  • 14