Search code examples
rokubrightscript

Remove Duplicate String and display unique String in Roku


I created a roAssociativeArray Object and add multiple strings in Roku. Like Below

Nikunj
Ronak
Raxit
Suhag
Nikunj
Suhag
Suhag
Nikunj
Ronak
Nikunj

here I tried to remove a duplicate value and display only unique value. Is It possible in Roku? I needed below output :

Nikunj
Ronak
Raxit
Suhag

In C# Its possible like below

ChDate = ChDate.Distinct().ToList();

But I don't know how Is it work in Roku.


Solution

  • Roku does not have a built-in method to extract unique values from an array, you have to build your own.

    There are multiple ways of implementing this, here's one option using a hash table (associative array) to keep track of all the stored values:

    function unique(arr as Object)
      res = []
      table = {}
      for each v in arr
        k = v.toStr()
        if not table.doesExist(k)
          res.push(v)
          table[k] = true
        end if
      end for
      return res
    end function
    

    Usage:

    dupValues = ["Nikunj", "Ronak", "Raxit", "Suhag", "Nikunj", "Suhag", "Suhag", "Nikunj", "Ronak", "Nikunj"]
    uniqueValues = unique(dupValues)
    ?"uniqueValues "uniqueValues
    

    Output:

    [ "Nikunj", "Ronak", "Raxit", "Suhag" ]

    Notice how before storing into the hash table, the value is converted to a string (in case is not), this is so that this function can also accept an array of numbers.

    dupValues = [3, 3, 4, 1, 6, 7, 6]
    uniqueValues = unique(dupValues)
    ?"uniqueValues "uniqueValues
    

    Output:

    [ 3, 4, 1, 6, 7 ]