JS study notes-map/reduce

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
2
3
4
5
6
7
8
9
'use strict';

function pow(x) {
return x * x;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);

Other example:

1
2
3
4
// transfer the numbers in an array to string

var arr = [1,2,3,4,5,6,7,8,9];
arr.map(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']

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
2
3
4
var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
return x + y;
}); // 25
  • Use reduce() to get the product:
1
2
3
4
5
function product(arr) {
return arr.reduce(function(x, y) {
return x * y;
})
}
  • string2int(transfer a string to an int):
1
2
3
4
5
6
7
8
9
10
11
12
_MY_GLOBAL.string2int = function(s) {
var arr = [];
for (var c of s) {
if (!_MY_GLOBAL.isDigit(c)) {
throw `${c} is not a digit!`;
}
arr.push(_MY_GLOBAL.INTEGER.get(c));
}
return arr.reduce(function(x,y) {
return x * 10 + y;
});
};
  • Normalize the english names in an array (let the first letter in uppercase and the others in lowercase):
1
2
3
4
5
_MY_GLOBAL.normalize = function(arr) {
return arr.map(function norm_helper(s) {
return s.slice(0,1).toUpperCase() + s.slice(1,).toLowerCase();
});
};
  • A tricky use case when using map:
1
2
3
4
5
6
'use strict';

var arr = ['1', '2', '3'];
var r;
r = arr.map(parseInt);
console.log(r); //1,NaN,NaN

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
2
3
4
5
6
7
8
9
10
11
由于map()接收的回调函数可以有3个参数:callback(currentValue, index, array),
通常我们仅需要第一个参数,而忽略了传入的后面两个参数。不幸的是,
parseInt(string, radix)没有忽略第二个参数,导致实际执行的函数分别是:

parseInt('0', 0); // 0, 按十进制转换

parseInt('1', 1); // NaN, 没有一进制

parseInt('2', 2); // NaN, 按二进制转换不允许出现2

可以改为r = arr.map(Number);,因为Number(value)函数仅接收一个参数。

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
2


Array.prototype.indexOf()

String.prototype.trim()

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
2


More info: reference on Mozilla

0%