Js-three high order function filter-map-reduce, need to master, very easy to use, really sweet warning.

filter

  • Filter = filter

The filter method creates a new array of elements by checking all the eligible elements in the specified array. The parameter requirement in filter is a callback function that returns a Boolean value

  • If the Boolean value is true, the function automatically adds the n of the callback to the new array and continues
  • If the Boolean value is false, the function internally filters out the n and continues to filter out the rest
  • Note: The filter method alters the original array.
/ / example: An array num, Const num = [2, 11, 5, 20, 7, 30] let newNum = num. Filter (function (n){return n < 10 // }) console.log(newNum) // Results in [2, 5, 7]Copy the code

map

  • Map stands for enumeration and can also be filtered

The map() method returns a new array whose elements are the values of the original array elements processed by the callback. The map() method processes the elements in their original array order.

  • Note: Map () does not detect empty arrays.
  • Note: The map() method does not change the original array.
/ / example: Const num = [2, 5, 7, 3] let newNum = num.map(function (n){return n*2; }) console.log(newNum) // Results in [4, 10, 14, 6]Copy the code

reduce

The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value. Reduce () can be used as a higher-order function for compose of functions.

  • Note: Reduce () does not perform a callback for an empty array.
  • The reduce method is used to summarize all contents in an array, including sum, subtraction, multiplication, and division
// Reduce syntax: array.reduce(function(total, currentValue, currentIndex, ARR),initialValue) // Reduce method takes two arguments, // first argument: A callback function, which also takes two arguments, prevalue and one argument // The second argument: an initial value, usually set to 0, can be set as appropriateCopy the code

To better understand it, consider the following examples:

/ / example: An array num, Const num = [2, 5, 7, 3] let newNum = num.reduce(function (prevalue, N){return prevalue + n //prevalue = 0}, 0) console.log(newNum) // returns 17Copy the code
  • Conclusion: the above writing method can be changed to ES6 support arrow function writing method, you can try.
  • More use of this kind of higher order function method can greatly improve efficiency.