Web Dev
EN
Five Interesting Ways to Use Array.reduce() (And One Boring Way)
[]
24 ways
How Array.reduce() worksMost of the modern array methods return a new array.
The syntaxThe Array.reduce() accepts two arguments: a callback method to run against each item in the array, and a starting value.
In the callback, we add the current value to the sum , which has our starting value of 0 on the first loop, then 1 (the starting value of 0 plus the item value of 1 ), then 3 (the sum value of 1 plus the item value of 2 ), and so on.
One way you could do that is by using the Array.filter() method to get back just wizards whose house property is Hufflepuff .
// Get the names of the wizards in Hufflepuff var hufflepuff = wizards.reduce(function (newArr, wizard) { if (wizard.house === 'Hufflepuff') { newArr.push(wizard.name); } return newArr; }, []);Here’s another demo.
['wizards'
'array'
'interesting'
'hufflepuff'
'wizard'
'house'
'way'
'arrayreduce'
'return'
'item'
'object'
'ways'
'value'
'boring']