Swift: How can I remove duplicates from an array of doubles?

前端 未结 3 1017
栀梦
栀梦 2021-01-17 07:09

I have an array of values like [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.004000000000

3条回答
  •  星月不相逢
    2021-01-17 07:32

    You can use NumberFormatter to fix the minimum and maximum fraction digits and use a set to filter the duplicate elements:

    let array = [0.75, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0050000000000000001, 0.0040000000000000001]
    
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    numberFormatter.minimumFractionDigits = 3
    numberFormatter.maximumFractionDigits = 3
    

    var set = Set()
    let orderedSet: [Double] = array.flatMap {
        guard let string = numberFormatter.string(for: $0) else { return nil }
        return set.insert(string).inserted ? $0 : nil
    }
    
    orderedSet   // [0.75, 0.005, 0.004]
    

    If you need Strings (as suggested by @Hamish):

    var set = Set()
    let orderedSet: [String] = array.flatMap {
        guard let string = numberFormatter.string(for: $0) else { return nil }
        return set.insert(string).inserted ? string : nil
    }
    
    orderedSet   // ["0.750", "0.005", "0.004"]
    

提交回复
热议问题