[iOS] Array的sort, filter, map, reduce 函式
Sort
1.
var intArray = [342, 13, 12, 288, 3, 34, 2, 39, 596, 2]
intArray.sort()
print(intArray)
// output: [2, 2, 3, 12, 13, 34, 39, 288, 342, 596]
2.
var intArray = [342, 13, 12, 288, 3, 34, 2, 39, 596, 2]
intArray.sort(by: {$0 > $1})
print(intArray)
// output: [596, 342, 288, 39, 34, 13, 12, 3, 2, 2]
Filter
let intArray = [342, 13, 12, 288, 3, 34, 2, 39, 596, 2]
let newArray = intArray.filter({$0 % 2 == 0}) //過濾, 取偶數
print(newArray)
// output: [342, 12, 288, 34, 2, 596, 2]
Map
let intArray = [342, 13, 12, 288, 3, 34, 2, 39, 596, 2]
let newArray = intArray.map({$0 * 3}) //所有數值乘3倍
print(newArray)
// output: [1026, 39, 36, 864, 9, 102, 6, 117, 1788, 6
Reduce
let intArray = [342, 13, 12, 288, 3, 34, 2, 39, 596, 2]
let sum = intArray.reduce(0, {$0 + $1}) // sum從0開始, 所有數字的總和
print(sum)
// output: 1331
Last updated