按字符串数组中的唯一索引对值进行分组

时间:2016-05-04 07:40:25

标签: arrays vbscript asp-classic unique

如何只检索此示例的唯一数组。

"58|270,58|271,58|272,59|270,59|271,59|272"

我想将此数组存储为:

"58,270,271,272|59,270,271,272"

有人可以帮助我使用ASP经典或VB脚本

2 个答案:

答案 0 :(得分:1)

这不是一个直截了当的问题,在我最终想到一种方法之前,我发现自己已经考虑了几分钟。

要从指定的输入生成输出,需要某种自定义反序列化/序列化方法。下面的代码创建了一个2D数组,它将包含唯一索引(58,59等),并用相关值的逗号分隔列表填充它们(像这样做,以使其成为序列化简单)

结构方面,在反序列化时它看起来像这样

----- Array Debug ------
data(0, 0) = 58
data(1, 0) = 270,271,272
data(0, 1) = 59
data(1, 1) = 270,271,272

然后我们使用它作为以所需格式构建序列化字符串的基础。

'Function takes string input in the form <index>|<value>, ... extracts
'them into a 2D array groups duplicate indexes together.
Function DeserialiseToCustomArray(str)
  Dim a1, a2, x, y, idx
  If Len(str & "") > 0 Then
    a1 = Split(str, ",")
    ReDim data(1, 0)
    For x = 0 To UBound(a1)
      a2 = Split(a1(x), "|")
      If IsArray(data) Then
        idx = -1
        'Check for duplicates
        For y = 0 To UBound(data, 2)
          If data(0, y) = a2(0) Or IsEmpty(data(0, y)) Then
            idx = y
            Exit For
          End If
        Next

        'No duplicate found need to add a new element to the array.
        If idx = -1 Then
          idx = UBound(data, 2) + 1
          ReDim Preserve data(1, idx)
        End If
        data(0, idx) = a2(0)
        If IsEmpty(data(1, idx)) Then
          data(1, idx) = a2(1)
        Else
          data(1, idx) = Join(Array(data(1, idx), a2(1)), ",")
        End If
      End If
    Next
  End If
  DeserialiseToCustomArray = data
End Function

'Function takes a 2D array built from DeserialiseToCustomArray() and
'serialises it into a custom string in the form <index>,<value>, ... | ...
Function SerialiseArray(data)
  Dim x, y
  Dim str: str = Empty
  If IsArray(data) Then
    For y = 0 To UBound(data, 2)
      If y > 0 And y <= UBound(data, 2) Then str = str & "|"
      str = str & data(0, y) & "," & data(1, y)
    Next
  End If
  SerialiseArray = str
End Function

一些用法示例:

Dim str: str = "58|270,58|271,58|272,59|270,59|271,59|272"
Dim data, result

data = DeserialiseToCustomArray(str)
result = SerialiseArray(data)
WScript.Echo "input: " & str
WScript.Echo "output: " & result

输出:

Result: 58,270,271,272|59,270,271,272
Dim str: str = "58|270,58|271,58|272,59|270,59|271,59|272,60|345,61|345,58|270,60|200"
Dim data, result

data = DeserialiseToCustomArray(str)
result = SerialiseArray(data)
WScript.Echo "input: " & str
WScript.Echo "output: " & result

输出:

Result: 58,270,271,272,270|59,270,271,272|60,345,200|61,345
  

注意:如果在经典ASP中使用这些示例,请删除WScript.Echo并替换为Response.Write

答案 1 :(得分:0)

从数组中获取唯一项的常用方法是将它们作为键放入Dictionary

a = Array(58, 270, 271, 272, 270, 271, 272)

Set d = CreateObject("Scripting.Dictionary")
For Each i In a
  d(i) = True   'value can be anything, relevant is using i as key
Next

WScript.Echo Join(d.Keys, ",")  'Output: 58,270,271,272