幫你精通JS:函數式編程的七件武器之Reduce與Map
JavaScript是當今流行語言中對函數式編程支持最好的編程語言。函數式編程的七個函數分別為:
- - reduce() and reduceRight() to apply an operation to a whole array, reducing it to a single result
- - map() to transform one array into another by applying a function to each of its elements
- - flat() to make a single array out of an array of arrays
- - flatMap() to mix together mapping and flattening
- - forEach() to simplify writing loops by abstracting the necessary looping code
以及 search 與 selection 的函數:
- - filter() to pick some elements from an array
- - find() and findIndex() to search for elements that satisfy a condition
- - A pair of predicates, every() and some(), to check an array for a Boolean test
一、array.reduce() 將數列降維至一個值
當我們處理array的時候,總是陷入到無窮盡的loop循環之中,掉入進瑣碎的陷阱,戕害我們的思維和大腦。
reduce的基本工作原理如下:

求數列的和
首先從耳熟能詳的求數列之和起步。
- const myArray = [22, 9, 60, 12, 4, 56];
- const sum = (x, y) => x + y;
- const mySum = myArray.reduce(sum, 0); // 163
觀察其運行軌跡:
- #+begin_src js :results output
- const myArray = [22, 9, 60, 12, 4, 56];
- const sumAndLog = (x, y) => {
- console.log(`${x}+${y}=${x + y}`);
- return x + y;
- };
- myArray.reduce(sumAndLog, 0);
- #+end_src
- #+RESULTS:
- : 0+22=22
- : 22+9=31
- : 31+60=91
- : 91+12=103
- : 103+4=107
- : 107+56=163
求均值
有了reduce,我們得以用“描述”的方式,以decalratively的方式求得average:
- const average = arr => arr.reduce(sum, 0) / arr.length;
- console.log(average(myArray)); // 27.166667
求均值的第二種方法,將length寫到里面:
- const average2 = (sum, val, ind, arr) => {
- sum += val;
- return ind === arr.length - 1 ? sum / arr.length
- : sum; //將這作為思考的原材料
- };
- console.log(myArray.reduce(average2, 0)); // 27.166667s
更近一步,將average作為固有屬性:
- Array.prototype.average = function() {
- return this.reduce((x, y) => x + y, 0) / this.length;
- };
- let myAvg = [22, 9, 60, 12, 4, 56].average(); // 27.166667
單詞計算多個值
雖然 reduce 只能返回單個結果,但是此返回結果卻可以包含多個元素,比如是object。
- const average3 = arr => {
- const sumCount = arr.reduce(
- (accum, value) => ({sum: value + accum.sum, count: accum.count + 1}),
- {sum: 0, count: 0}
- );
- return sumCount.sum / sumCount.count;
- };
- console.log(average3([7, 11, 19, 23]));
以array的方式改寫:
- const average4 = arr => {
- const sumCount = arr.reduce(
- (accum, value) => [accum[0] + value, xaccum[1] + 1],
- [0, 0]
- );
- return sumCount[0] / sumCount[1];
- };
- console.log(average4(myArray)); // 27.166667
從右往左的折疊
工作原理如下圖:

比如 reverse 字符串的常規解決方案為:
- const reverseString = str => {
- let arr = str.split("");
- arr.reverse();
- return arr.join("");
- };
- console.log(reverseString("MONTEVIDEO")); // OEDIVETNOM
而reduceRight的解題方案呢,
- const reverseString2 = str =>
- str.split("").reduceRight((x, y) => x + y, "");
- console.log(reverseString2("OEDIVETNOM")); // MONTEVID
二、array.map 從數學到編程
map首先是數學上的概念。

從object中提取數據
- const markers = [
- {name: "AR", lat: -34.6, lon: -58.4},
- {name: "BO", lat: -16.5, lon: -68.1},
- {name: "BR", lat: -15.8, lon: -47.9},
- {name: "CL", lat: -33.4, lon: -70.7},
- {name: "CO", lat: 4.6, lon: -74.0},
- {name: "EC", lat: -0.3, lon: -78.6},
- {name: "PE", lat: -12.0, lon: -77.0},
- {name: "PY", lat: -25.2, lon: -57.5},
- {name: "UY", lat: -34.9, lon: -56.2},
- {name: "VE", lat: 10.5, lon: -66.9},
- ];
- let averageLat = average(markers.map(x => x.lat)); // -15.76
- let averageLon = average(markers.map(x => x.lon)); // -65.53
- // extended array.prototype
- let averageLat2 = markers.map(x => x.lat).average();
- let averageLon2 = markers.map(x => x.lon).average();
悄無聲息的處理數據
看一個我們想當然的應用:
- ["123.45", "67.8", "90"].map(parseFloat);
- // [123.45, 67.8, 90]
- ["123.45", "-67.8", "90"].map(parseInt);
- // [123, NaN, NaN]
這是因為 parseInt 有一個 optional 的參數 radix。
數列的表示方法
現在我們來創建一個 range.
- const range = (start, stop) =>
- new Array(stop - start).fill(0).map((v, i) => start + i);
- // 必須寫一個v,也必須寫 new
- let from2To6 = range(2, 7); // [2, 3, 4, 5, 6]
嘗試求乘方:
- const range = (start, stop) =>
- new Array(stop - start).fill(0).map((v, i) => start + i);
- const factorialByRange = n => range(1, n + 1).reduce((x, y) => x * y, 1);
- factorialByRange(5); // 120
- factorialByRange(3);
嘗試字母表:
- const ALPHABET = range("A".charCodeAt(), "Z".charCodeAt() + 1).map(x =>
- String.fromCharCode(x)
- );
- // ["A", "B", "C", ... "X", "Y", "Z"]
用 reduce 構造 map
reduce是所有其他函數的起點,
- const myMap = (arr, fn) => arr.reduce((x, y) => x.concat(fn(y)), []);
嘗試兩種不同的解決方案:
- const myArray = [22, 9, 60, 12, 4, 56];
- const dup = x => 2 * x;
- console.log(myArray.map(dup)); // [44, 18, 120, 24, 8, 112]
- console.log(myMap(myArray, dup)); // [44, 18, 120, 24, 8, 112]
- console.log(myArray); // [22, 9, 60, 12, 4, 56]
【編輯推薦】