### 1. `map()`方法

``````var new_array = arr.map(callback[, thisArg])
``````

• Example
``````// for loop
var arr = [1, 3, 5, 7, 9];
var new_array = new Array(arr.length);
for(var i = 0; i < arr.length; i++) {
new_array[i] = arr[i] * arr[i];
}
``````
``````// map()
var arr = [1, 3, 5, 7, 9];
var new_array = arr.map(function(ele) {
return ele * ele;
})
``````

### 2. `filter()`方法

``````var new_array = arr.filter(callback[, thisArg])
``````

• Example
``````var arr = [1, 2, 1, 3, 4, 1, 5, 1];
var new_array = arr.filter(function(ele) {
return ele !== 1;
})
``````

### 3. `every()`方法

`filter()`类似，只不过`every()`返回的是一个布尔值，用来判断是否数组中所有元素都满足回调函数的条件。

``````arr.every(callback[, thisArg])
``````
• Example
``````var arr = [1, 2, 3, 4, 5, 6, 7];
arr.every(x => x >=5);
``````

### 4. `reduce()`方法

``````arr.reduce(callback, [initialValue])
``````

`reduce()`接受的回调函数是用来把数组所有元素减少到一个值，听起来有点懵，看两个例子好了。

• 栗子一
``````var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(acc, val) {
return acc * val;
})
// 24
``````

• 栗子二
``````var str = ['a', 'b', 'c', 'd', 'e'];
var new_str = str.reduce(function(acc, val) {
return acc.concat(val);
})
// 'abcde'
``````

• 栗子三
``````var arr = [[1, 2], [3, 4, 5], [6, 7, 8, 9]];
var new_arr = arr.reduce(function(acc, val) {
acc.concat(val);
})
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
``````

### `purrr`包经典函数：`map()`家族

``````# .x is list or vector, .f is function or formular
map(.x, .f, ...)
``````

• 栗子一
``````1:10 %>%
map(function(x) x ^ 2)
``````
• 栗子二
``````1:10 %>%
map(~ .x + 1)
``````

``````1:10 %>%
map_dbl(function(x) x ^ 2)
``````

`flatten()`一次只能拍扁一下，啥意思呢？就是它只能每次把最外层list拍扁一下，拍完了还是list

``````list1 <- list(list(c(1, 2, 3), c(2, 3, 4)), c(3, 4, 5))
flatten(list1)
``````

``````flatten(list1) %>%
flatten()
``````

``````flatten(list1) %>%
flatten() %>%
flatten_dbl()
``````

### `reduce()`家族

``````a <- 1:7 %>%
reduce(`-`)
# -26
``````

`reduce_right()`是从右向左来递归。`accumulate()`会把中间结果给出来。

### `every()`

``````a <- 1:10
a %>%
every(function(x) {
x < 11
})
# TRUE
``````

javascript R
`map()` `map()`家族
`reduce()` `reduceRight()` `reduce()`家族
`every()` `every()`
`some()` `some()`
`indexOf()` `lastIndexOf()` `detect_index()`
`find()` `detect()`
`invoke()` `invoke()`家族
`flatten()` `flatten()`家族
`negate()` `negate()`
`...` `...`

``````nums = sc.parallelize([1, 2, 3, 4])
squared = nums.map(lambda x: x * x).collect()
``````
``````val input = sc.parallelize(List(1, 2, 3, 4))
val result = input.map(x => x * x)
``````