September 2018
Intermediate to advanced
302 pages
7h 17m
English
Our next example is about counting the items in an array. Let's say you have an array of house items. You need to count how many of each you own. Using the reduce function, the expected outcome is an object with items as keys and a count of particular items as values, as follows:
const items = ['fork', 'laptop', 'fork', 'chair', 'bed', 'knife', 'chair'];items.reduce((acc, elem) => ({ ...acc, [elem]: (acc[elem] || 0) + 1 }), {});// {fork: 2, laptop: 1, chair: 2, bed: 1, knife: 1}
This is quite tricky: the part (acc[elem] || 0) means we either take the value of acc[elem], if it is defined, or otherwise, 0. This way, we check for the first element of its kind. Also, { [elem]: something } is syntax used to define a ...
Read now
Unlock full access