Map/Reduce
1. map
For example, there is a function f(x) = x * x. If you want to call this function on every element in an array, you can use map():
1 | 'use strict'; |
Other example:
1 | // transfer the numbers in an array to string |
More info: reference on Mozilla
2. reduce
Brief Definition
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
1 | [x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4) |
Some Usage
- Use reduce() to get the sum of all integers in an array:
1 | var arr = [1, 3, 5, 7, 9]; |
- Use reduce() to get the product:
1 | function product(arr) { |
- string2int(transfer a string to an int):
1 | _MY_GLOBAL.string2int = function(s) { |
- Normalize the english names in an array (let the first letter in uppercase and the others in lowercase):
1 | _MY_GLOBAL.normalize = function(arr) { |
- A tricky use case when using map:
1 | 'use strict'; |
Why can’t this map() work out for transfering the strings to ints?
Reference to the original post;
Reference to "Array.prototype.map()";
Reference to "basic of callback";
Reference to "parseInt";
Solution:
1 | 由于map()接收的回调函数可以有3个参数:callback(currentValue, index, array), |
Reference to “Number()”;
More info: reference on Mozilla
3. filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
1 |
More info: reference on Mozilla
4. sort
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
1 |
More info: reference on Mozilla