// friends - an array of objects // where object field "books" - list of favorite books var friends = [{ name: 'Anna', books: ['Bible', 'Harry Potter'], age: 21 }, { name: 'Bob', books: ['War and peace', 'Romeo and Juliet'], age: 26 }, { name: 'Alice', books: ['The Lord of the Rings', 'The Shining'], age: 18 }];
// 如果 initialValue 沒有傳會造成 undefined is not a function 的 Exception // allbooks - list which will contain all friends' books + // additional list contained in initialValue var allbooks = friends.reduce(function(prev, curr) { return [...prev, ...curr.books]; }, []);
// allbooks = [ // 'Bible', 'Harry Potter', 'War and peace', // 'Romeo and Juliet', 'The Lord of the Rings', // 'The Shining' // ]
Array.prototype.reduceRight()
與 Array.prototype.reduce() 的差別,是從右邊開始執行。
reduceRight
js
1 2 3 4 5 6
var a = ['1', '2', '3', '4', '5']; var left = a.reduce(function(prev, cur) { return prev + cur; }); var right = a.reduceRight(function(prev, cur) { return prev + cur; });