reduce
by trentHarlem
JavaScript
let arr = [1, 2, 3, 4]
//declare a function then use the function with reduce method
const add = (a, b) => a + b
const subtract = (a, b) => a - b
const multipy = (a, b) => a * b
const divide = (a, b) => a / b
console.log('reduce w/ function', arr.reduce(add))
// or use the function expression INSIDE the reduce method
console.log('reduce w/func expr', arr.reduce((acc, cur) => acc = acc + cur))
//console.log('reduce w/ subtract', arr.reduce(subtract))
//console.log('reduce w/ multiply', arr.reduce(multipy))
//console.log('reduce w/ divide', arr.reduce(divide))
//-------------------------------------------
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(accumulator, currentValue) {
return [...accumulator,...currentValue]
//return accumulator.concat(currentValue)
},
[]
)
console.log(flattened)
//-------------------------------------------
let categories = ['Healthcare', 'Finance', 'Insurance', 'Retail', 'Healthcare']
let counted = categories.reduce(function(allCats, category) {
if (category in allCats) {
allCats[category]++
} else {
allCats[category] = 1
}
//console.log(allCats)
return allCats
}, {})
//console.log(counted)
// counted is:
//{ Finance: 1, Healthcare: 2, Insurance: 1, Retail: 1 }
//----------------------------------------------------------
// friends - an array of objects
// where object field "books" is a list of favorite books
let 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
}]
// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
let allbooks = friends.reduce(function(accumulator, currentValue) {
return [...accumulator, ...currentValue.books]
}, ['Alphabet'])
console.log(allbooks)
// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// ...