js array map, filter, reduce

filter 

filter, filter elements in an array according to certain conditions

  选择数组中值大于3的组合为新数组
  a.filter((item) => item > 3)

Syntax

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

Parameters

callback

Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise, taking three arguments:

element

The current element being processed in the array.

indexOptional

The index of the current element being processed in the array.

arrayOptional

The array filter was called upon.

thisArg Optional

Optional. Value to use as this when executing callback.

 

map

Map, map the elements in the array to a new array according to certain rules

新数组中的元素是a中的数的平方
a.map(
    (item) => item * item
  )

Syntax

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

Parameters

callback

Function that produces an element of the new Array, taking three arguments:

 

currentValue

The current element being processed in the array.

indexOptional

The index of the current element being processed in the array.

arrayOptional

The array map was called upon.

thisArgOptional

Value to use as this when executing callback.

 

 

reduce

Aggregation, the array is aggregated into a result in a certain way, this result is not just a number, it can be an object or an array! ! !

对a中的数字求和
a.reduce(
    (pre, cur) => pre += cur,
    0
  )

 

将a中的数字连接成字符串
a.reduce(
    (pre, cur) => pre += cur,
    ''
  )

 

对于a中的元素,如果该元素的平方比4大,则将该数的平方放入新数组
只使用map或filter是做不到的
a.reduce(
    (pre, cur) => {
      let ret = cur * cur
      if (ret > 4)
        pre.push(ret)
      return pre
    },
    []
  )
统计a中每个数字出现的次数,返回一个对象
对象的键是a中的数字种类,值是该数出现的次数
a.reduce(
    (pre, cur) => {
      pre[cur] = pre[cur] ? ++pre[cur] : 1
      return pre
    },
    {}
  )

同样的功能,使用逗号表达式和三元表达式简化箭头函数
 a.reduce(
    (pre, cur) => (pre[cur] ? pre[cur]++ : pre[cur] = 1, pre),
    {}
  )

 

Syntax

arr.reduce(callback[, initialValue])

Parameters

callback

Function to execute on each element in the array, taking four arguments:

accumulator

The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).

currentValue

The current element being processed in the array.

currentIndexOptional

The index of the current element being processed in the array. Starts at index 0, if an initialValue is provided, and at index 1 otherwise.

arrayOptional

The array reduce() was called upon.

initialValueOptional

Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325342024&siteId=291194637