|
| 1 | +const array1 = [1, 2, 3, 4] |
| 2 | +const log = console.log |
| 3 | + |
| 4 | +log() |
| 5 | + |
| 6 | +const reducer = (accumulator, currentValue) => accumulator + currentValue |
| 7 | + |
| 8 | +// 1 + 2 + 3 + 4 |
| 9 | +log('1 + 2 + 3 + 4 = ', array1.reduce(reducer),0) |
| 10 | +// expected output: 10 |
| 11 | + |
| 12 | +// 5 + 1 + 2 + 3 + 4 |
| 13 | +log('5 + 1 + 2 + 3 + 4 = ', array1.reduce(reducer, 5)) |
| 14 | +// expected output: 15 |
| 15 | + |
| 16 | +log() |
| 17 | +// Counting instances of values in an object |
| 18 | +let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'] |
| 19 | + |
| 20 | +let countedNames = names.reduce(function (allNames, name) { |
| 21 | + if (name in allNames) { |
| 22 | + allNames[name]++ |
| 23 | + } else { |
| 24 | + allNames[name] = 1 |
| 25 | + } |
| 26 | + return allNames |
| 27 | +}, {}) |
| 28 | + |
| 29 | +log('countedNames', countedNames) |
| 30 | +log() |
| 31 | +// countedNames is: |
| 32 | +// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 } |
| 33 | + |
| 34 | +// Grouping objects by a property |
| 35 | +let people = [ |
| 36 | + { name: 'Alice', age: 21 }, |
| 37 | + { name: 'Max', age: 20 }, |
| 38 | + { name: 'Jane', age: 20 }, |
| 39 | +] |
| 40 | + |
| 41 | +function groupBy(objectArray, property) { |
| 42 | + return objectArray.reduce(function (acc, obj) { |
| 43 | + let key = obj[property] |
| 44 | + if (!acc[key]) { |
| 45 | + acc[key] = [] |
| 46 | + } |
| 47 | + acc[key].push(obj) |
| 48 | + return acc |
| 49 | + }, {}) |
| 50 | +} |
| 51 | + |
| 52 | +let groupedPeople = groupBy(people, 'age') |
| 53 | +log('groupedPeople', groupedPeople) |
| 54 | +log() |
| 55 | +// groupedPeople is: |
| 56 | +// { |
| 57 | +// 20: [ |
| 58 | +// { name: 'Max', age: 20 }, |
| 59 | +// { name: 'Jane', age: 20 } |
| 60 | +// ], |
| 61 | +// 21: [{ name: 'Alice', age: 21 }] |
| 62 | +// } |
0 commit comments