> For the complete documentation index, see [llms.txt](https://frost.gitbook.io/iosbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://frost.gitbook.io/iosbook/ios/ios-book/ios-array-de-sort-filter-map-reduce-han-shi.md).

# \[iOS] Array的sort, filter, map, reduce 函式

## Sort

1\.

```swift
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\.

```swift
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

```swift
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

```swift
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

```swift
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
```
