Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find unique values in a Swift Array

I am building a project that tells me the unique words in a piece of text.

I have my orginal string scriptTextView which I have added each word into the array scriptEachWordInArray

I would now like to create an array called scriptUniqueWords which only includes words that appear once (in other words are unique) in scriptEachWordInArray

So I'd like my scriptUniqueWords array to equal = ["Silent","Holy"] as a result.

I don't want to create an array without duplicates but an array that has only values that appeared once in the first place.

var scriptTextView = "Silent Night Holy Night"
var scriptEachWordInArray = ["Silent", "night", "Holy", "night"]
var scriptUniqueWords = [String]()

for i in 0..<scriptEachWordInArray.count {

    if scriptTextView.components(separatedBy: "\(scriptEachWordInArray[i]) ").count == 1 {
        scriptUniqueWords.append(scriptEachWordInArray[i])
        print("Unique word \(scriptEachWordInArray[i])")}

}
like image 918
flakedev Avatar asked Dec 10 '22 13:12

flakedev


1 Answers

You can use NSCountedSet

let text = "Silent Night Holy Night"
let words = text.lowercased().components(separatedBy: " ")
let countedSet = NSCountedSet(array: words)
let singleOccurrencies = countedSet.filter { countedSet.count(for: $0) == 1 }.flatMap { $0 as? String }

Now singleOccurrencies contains ["holy", "silent"]

like image 188
Luca Angeletti Avatar answered Jan 12 '23 20:01

Luca Angeletti