JavaScript higher-order functions map/reduce, filter, and sort

Source: Internet
Author: User
Tags javascript array

Map ()

For example, for example, we have a function f (x) =x2, to function on an array [1,2,3,4,5,6,7,8,9].

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:

function Pow (x) {        return x*x;    }     var arr = [1,2,3,4,5,6,7,8,9];    Arr.map (POW); // [1,4,9,16,25,36,49,64,81]

Map () The parameter passed in is the POW, which is the function object itself.

Map () as a higher order function, in fact it abstracts the rules of operation, because we can not only calculate the simple f (x) =x2, but also can calculate arbitrary complex functions, such as the array of all the numbers into a string:

var arr = [1,2,3,4,5,6,7,8,9];    Arr.map (String); // [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']    // only one line of code is needed

Reduce ()

Looking again at the usage of reduce, the reduce () of array uses a function in this array [x1,x2,x3 ...] On This function must receive two parameters, and reduce () will accumulate the result and the next element of the sequence, the effect is

[X1,x2,x3,x4].reduce (f) = f (f (f (x1,x2), x3), x4)

For example, to sum an array, you can use reduce to achieve:

var arr = [1,3,5,7,9];    Arr.reduce (function(x, y        ) {return x+y;    }); //  -

converting [1,3,5,7,9] to Integer 13579,reduce () can also come in handy:

var arr = [1,3,5,7,9];    Arr.reduce (function(x, y        ) {return x*10+y;    }); // 13579

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:

var arr = [1,2,4,5,6,9,10,15];     var r = Arr.filter (function(x) {        return x% 2!== 0;    });    R; // [1,5,9,15]

To delete an empty string in an array, you can write:

var arr=[' A ', ' ', ' B ',null, Undefined, ' C ', '];     var r=arr.filter (function(s) {        return s && s.trim ();   Note that the IE9 version has no trim () method     });    R; // [' A ', ' B ', ' C ']

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

callback function

The callback function that the filter () receives 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:

var arr = [' A ', ' B ', ' C '];     var r=arr.filter (function(element,index,self) {        console.log (element); // print ' A ', ' B ', ' C '        in turn Console.log (index); // Print 0,1,2        Console.log (self); // Self is the variable arr        return true ;    })

Sort

Sorting algorithm:

Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting. The core of the sort is to compare the size of two elements. If it is a number, we can compare it directly. But what if it's a string or two objects? There is no point in directly comparing the size of the numbers, so the process of comparison must be abstracted through functions. It is generally stipulated that for two elements x and Y, if X<y is considered, 1 is returned, if x==y, then 0 is returned, if the x>y is considered, then 1 is returned, so that the sorting algorithm does not care about the specific comparison process, but rather the direct ordering according to the results of the comparison.

The sort () method of the array is used for sorting. But the sort results can be a surprise to you.

This is because the sort () method of the array defaults to converting all elements first to string and the result ' 10 ' is preceded by ' 2 ' because the character ' 1 ' is smaller than the ASCII code of the character ' 2 '.

If you don't know the default collation of the sort () method, it's a surprise to sort the numbers directly.

Sort () is also a higher-order function. You can receive a comparison function to implement a custom sort.

var arr=[10,20,1,2];    Arr.sort (function(x, y        ) {if(x<y            ) {return -1;        }         if (x>y) {            return 1;        }         return 0;    }); // [1,2,10,20]

By default, the string is sorted by the size of ASCII, and now we propose that the sort 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:

  var  arr = [' Google ', ' apple ', ' Microsoft '  function   (S1,S2) {x1  =<        Span style= "COLOR: #000000" > 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 (or lowercase) the strings before comparing them.

The abstraction of higher-order functions is very powerful, and the core code can be kept very concise.

The sort () method modifies the array directly, and the result is still the current array:

var a1 = [' B ', ' A ', ' C '];     var a2 = a1.sort ();    A1; // [' A ', ' B ', ' C ']    A2; // [' A ', ' B ', ' C ']    A1 = = = A2; // TRUE,A1 and A2 are the same object. 

JavaScript higher-order functions map/reduce, filter, and sort

Related Article

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.