2017-02-26 44 views
0

我有一個數組循環數組,清除唯一值,只留下重複

allIDs = ["1", "2", "2", "3", "4", "4"] 

我用

sortedIDs = Array(Set(allIDs)) 

現在我想刪除的唯一字符串中做出獨特的內容allIDs數組,所以只剩下重複項。

for item in sortedIDs { 
while allIDs.contains(item) { 
    if let itemToRemoveIndex = allIDs.index(of: item) { 
     allIDs.remove(at: itemToRemoveIndex) 
     print(allIDs) 
    } 
} 

}

這給了我一個allIDs數組,它是空的。我難以理解應該循環四次的for循環是循環六次並刪除所有項目。 謝謝。

+0

@dtd這不是重複的。 OP已經知道如何刪除重複項。問題是創建一個只包含重複項的最終數組。 – rmaddy

+2

您的預期成果是什麼? '[「2」,「2」,「4」,「4」]還是'[「2」,「4」]? – Hamish

+0

我的不好。我會刪除我的評論。但我可能會建議編輯問題標題以反映實際問題。 – dfd

回答

0

我假設你想要的結果是["2", "4"];從原始數組中刪除重複數組以獲取sortedIDs數組。

您的問題是while循環正在循環,直到從allIDs中刪除項目的所有副本。如果您只需對sortedIDs中的每個項目執行1次刪除,就會得到您想要的結果:

for item in sortedIDs { 
    if let itemToRemoveIndex = allIDs.index(of: item) { 
     allIDs.remove(at: itemToRemoveIndex) 
     print(allIDs) 
    } 
}