如何过滤所有最高数字

时间:2017-11-20 12:14:05

标签: swift filter

我试图过滤掉数组中的最高数字

var a = [2, 2, 1, 1, 0]

var b = a.max()

print(b!) // 2

如何获得所有最高数字?

print (b!) // 2, 2

1 个答案:

答案 0 :(得分:0)

使用max()filter(_ isIncluded:)

let array: [Int] = [2, 2, 1, 1, 0]
let maxElement: Int? = array.max()

if let unwrappedMaxElement: Int = maxElement {
  let arrayContainingMaxElements: [Int] = array.filter { $0 == unwrappedMaxElement }

  print(arrayContainingMaxElements) // [2, 2]
}