Several common high-order functions in JS

Source: Internet
Author: User
Tags javascript array

Higher order function: English called Higher-order function. JavaScript functions actually point to a variable. Since the variable can point to a function, the function's arguments can receive the variable, then one function can receive another function as a parameter, which is called the higher order function.

One of the simplest high-order functions:

function Add (x, Y, f) {returnF (x) +f (y);}//when Add ( -5, 6, Math.Abs) is called, the parameters x, Y and F receive -5,6 and function Math.Abs respectively, and according to the function definition, the calculation process can be deduced as://x =-5;//y = 6;//f = math.abs;//f (x) + f (y) ==> Math.Abs ( -5) + math.abs (6) ==> one;//return one;//Verify with code:Add (-5,6, Math.Abs);// One

Writing higher-order functions allows the parameters of a function to receive other functions.

Here are three high-order functions:

First, Map/reduce

If you read Google's famous paper "Mapreduce:simplified Data processing on Large Clusters", you can probably understand the concept of map/reduce. Because the map () method is defined in the JavaScript array, we call the map () method of array and pass in our own function, and we get a new array as the result:

1. Map ():

function pow (x) {returnX *x;}vararr = [1,2,3,4,5,6,7,8,9];arr.map (POW); //[1, 4, 9, +, (+), +, +, Bayi]//map () The parameter passed in is the POW, which is the function object itself. //You do not need a map (), write a loop, or calculate the result:varf =function (x) {returnX *x;};vararr = [1,2,3,4,5,6,7,8,9];varresult = []; for(varI=0; i<arr.length; i++) {Result.push (f (arr[i]));}//yes, but, from the loop code above, we can't see at a glance "put f (x) in each element of the array and generate a new array". 

So, as a higher-order function, map () actually abstracts the arithmetic rules, so we can calculate not only the simple f (x) =x2, but also any complex function, such as converting all the numbers of an array to a string:

var arr = [123456789  //  [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']// only one line of code is required. 

2. Reduce ():

Let's look at the usage of reduce. The reduce () of the array functions a function on this array [x1, x2, x3 ...] , the function must receive two parameters, and reduce () accumulates the result and the next element of the sequence , with the effect of:

[X1, x2, X3, x4].reduce (f) = f (f ( f (x1, x2), x3), x4)// For example, summing an array can be implemented with reduce:var arr = [13579];arr.reduce (function (x, y) {      return x +//  

Second, filter

Filter is also a common operation, it is used to filter out some elements of the array, and then return the remaining elements. Like map (), the filter () of the array also receives a function. Unlike map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.

//For example, in an array, delete an even number, leaving only the odd number, which you can write:vararr = [1,2,4,5,6,9,Ten, the];varR =Arr.filter (function (x) {returnX%2!==0;}); R //[1, 5, 9, a]//To delete an empty string in an array, you can write:vararr = ['A',"','B',NULL, Undefined,'C','  '];varR =Arr.filter (function (s) {returnS && S.trim ();//Note: The following versions of IE9 do not have the trim () method}); arr; //[' A ', ' B ', ' C ']

The key is to implement a "filter" function correctly by using the filter () as a high-order function.

callback function: The callback function received by the filter () can actually have multiple parameters. Usually we use only the first parameter, which represents an element of an array. The callback function can also receive two additional parameters, representing the location of the element and the array itself:

vararr = ['A','B','C'];varR =arr.filter (function (element, index, self) {console.log (element);//print ' A ', ' B ', ' C ' in turnConsole.log (index);//print 0, 1, 2Console.log (self);//Self is the variable arr    return true;});//with filter, you can subtly remove the repeating elements of an array:'Use Strict';varR, arr= ['Apple','Strawberry','Banana','Pear','Apple','Orange','Orange','Strawberry'];r=arr.filter (function (element, index, self) {returnSelf.indexof (Element) = = =index;}); Alert (r.tostring ());//the removal of the repeating element relies on the indexof always returning the position of the first element, and the subsequent repetition of the element position is not equal to the position returned by the indexof, so it is filtered by the filter. 

Third, sort sorting algorithm

Because the sort () method of the array defaults to converting all elements to string reordering, the result ' 10 ' is preceded by ' 2 ' because the character ' 1 ' is smaller than the ASCII code of the character ' 2 '. If you do not know the default collation of the sort () method, sort the numbers directly, absolutely planted in the pits!

Fortunately, the sort () method is also a higher-order function, and it can also receive a comparison function to implement a custom sort.

//to sort by numerical size, we can write this:vararr = [Ten, -,1,2];arr.sort (function (x, y) {if(X <y) {return-1; }    if(X >y) {return 1; }    return 0;}); //[1, 2, ten,]//If you want to sort in reverse order, we can put the large number in front:vararr = [Ten, -,1,2];arr.sort (function (x, y) {if(X <y) {return 1; }    if(X >y) {return-1; }    return 0;}); //[Ten, 2, 1]//by default, the string is sorted by the size of ASCII, and now the sorting should be ignored in case, sorted alphabetically. //to implement this algorithm, you do not have to change the existing code, as long as we can define the ignoring case of the comparison algorithm can be:vararr = ['Google','Apple','Microsoft'];arr.sort (function (s1, s2) {x1=s1.touppercase (); X2=s2.touppercase (); if(X1 <x2) {        return-1; }    if(X1 >x2) {        return 1; }    return 0;}); //[' Apple ', ' Google ', ' Microsoft ']//ignoring the case to compare two strings is actually the first to capitalize the strings (or all lowercase) before comparing them. //The sort () method modifies the array directly, and the result is still the current array:varA1 = ['B','A','C'];varA2 =A1.sort (); A1;//[' A ', ' B ', ' C ']A2;//[' A ', ' B ', ' C ']A1 = = = A2;//True, A1 and A2 are the same object

Several common high-order functions in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.