- Array sum
[1, 2, 3, 4].reduce(function(a, b){ return a +b; }) // 10
- merge two array as key value pair
var columns = ["Date", "Number", "Size", "Location", "Age"]; var rows = ["2001", "5", "Big", "Sydney", "25"]; var result = rows.reduce(function(result, field, index) { result[columns[index]] = field; return result; }, {}) console.log(result); { Date: "2001", Number: "5", Size: "Big", Location: "Sydney", Age: "25" }
- flatten Array of Objects
var array = [{ key: 'one', value: 1 },{ key: 'two', value: 2 },{ key: 'three', value: 3 }]; array.reduce(function(obj, current) { obj[current.key] = current.value; return obj; }, {}); array.reduce((obj, current) => Object.assign(obj, { [current.key]: current.value }), {}); array.reduce((obj, current) => ({...obj, [current.key]: current.value}), {}); All of The above examples for flatten Array result in: { one: 1, two: 2, three: 3 }
-
Find Min or Max Value
var arr = [4, 2, 1, -10, 9] arr.reduce(function(a, b) { return a < b ? a : b }, Infinity); // → -10
-
Find Unique Values
var arr = [1, 2, 1, 5, 9, 5]; arr.reduce((prev, number) => { if(prev.indexOf(number) === -1) { prev.push(number); } return prev; }, []); // → [1, 2, 5, 9]