Hi folks!
My first post here is a question I'm facing atm, hope you can share some wisdom :)
Consider the following two approaches to creating an object of counts from an array of filters and a collection of items
(structure is irrelevant to the question):
Using reduce
const filterFields= ['filter1', 'filter2']
filterCounts = filterFields.reduce((filterCountsAccumulator, currentFilterField) => {
filterCountsAccumulator[currentFilterField] = getCounts(items, currentFilterField)
return filterCountsAccumulator
}, {})
Using forEach + object assignment
const filterFields= ['filter1', 'filter2']
filterCounts = {}
filterFields.forEach(currentFilterField => {
filterCounts[currentFilterField] = getCounts(items, currentFilterField)
})
I like the elegance of reduce
but find the forEach
approach much more readable as it more clearly shows the structure of the resulting filterCounts
object.
Is it just my inexperience with reduce
, or would you agree that forEach
communicates intent more clearly in this case?
Are there other reasons to prefer one approach over the other?
Many thanks in advance :)
Top comments (0)