1.map
Because the map() method is defined in JavaScript Array, we call Array's map() method and pass in our own function, and we get a new Array as a 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]
The parameter passed in by map() is pow, which is the function object itself.
You might think that without map(), you can write a loop and calculate the results.
As a higher-order function, map() abstracts the operation rules. Therefore, we can not only calculate simple f(x)=x2, but also calculate arbitrarily complex functions, such as converting all Array numbers into strings:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; arr.map(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']
It only takes one line of code.
2.reduce
Look again at the use of reduce. Array's reduce() applies a function to this Array's [x1, x2, x3...]. This function must accept two parameters. Reduc () continues the result and accumulates the next element of the sequence. Its 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; }); // 25
To convert [1, 3, 5, 7, 9] into integers 13579, reduce() can also be useful:
var arr = [1, 3, 5, 7, 9]; arr.reduce(function (x, y) { return x * 10 + y; }); // 13579
3.filter
filter is also a common operation that filters out some elements of Array and returns the remaining elements.
Similar to map(), Array's filter() also receives a function. Unlike map(), filter() acts on each element in turn, and then decides whether to retain or discard the element based on whether the return value is true or false.
For example, in an Array, delete even numbers and keep only odd numbers. You can write as follows:
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 from an Array, you can write as follows:
var arr = ['A', '', 'B', null, undefined, 'C', ' ']; var r = arr.filter(function (s) { return s && s.trim(); // Note: There is no trim() method for versions below IE9 }); r; // ['A', 'B', 'C']
It can be seen that the key to using filter() as a high-order function is to correctly implement a "filter" function.
3.1 callback function
The callback function received by filter() can actually have multiple parameters. Usually we only use the first parameter to represent an element of Array. The callback function can also receive two other 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 in turn console.log(self); // self is the variable arr return true;
});
Using filter, the repetitive elements of Array can be subtly removed:
'use strict'; var r, arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry']; r = arr.filter(function (element, index, self) { return self.indexOf(element) === index; });
Removing duplicate elements depends on indexOf always returning the position of the first element. The position of subsequent duplicate elements is not equal to that of indexOf, so it is filtered out by filter.
4.sort
JavaScript's Array sort() method is used for sorting, but the sorting results may surprise you:
// Seemingly normal results: ['Google', 'Apple', 'Microsoft'].sort(); // ['Apple', 'Google', 'Microsoft']; // apple came last: ['Google', 'apple', 'Microsoft'].sort(); // ['Google', 'Microsoft", 'apple'] // Ununderstandable results: [10, 20, 1, 2].sort(); // [1, 10, 2, 20]
The second sort ranks apple last because strings are sorted according to ASCII codes, while ASCII codes for lowercase a follow uppercase letters.
What's the result of the third sort? Can simple numbers be sorted incorrectly?
This is because Array's sort() method defaults to converting all elements to String before sorting, resulting in'10'ahead of'2' because the character'1'is smaller than the ASCII code of the character'2'.
To sort by number size, we can write as follows:
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]
If we want to sort in reverse order, we can put the large number in front:
var arr = [10, 20, 1, 2]; arr.sort(function (x, y) { if (x < y) { return 1; } if (x > y) { return -1; } return 0; }); // [20, 10, 2, 1]
By default, string sorting is compared according to the size of ASCII. Now, we propose that sorting should ignore case and sort alphabetically. To implement this algorithm, we do not need to make any major changes to the existing code, as long as we can define a comparison algorithm that ignores case.
var arr = ['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']
At the end of the friendship note, the sort() method directly modifies Array, and it returns 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 objects