counting items using reduce
Thu Apr 04 2024 01:28:36 GMT+0000 (Coordinated Universal Time)
Saved by
@davidmchale
#javascript
#reduce
#counting
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];
const transportation = data.reduce((total, item) => {
if(!total[item]){
total[item] = 0
}
total[item]++
return total
},{})
console.log(transportation)
/** Dynamic property access (using []):
The square bracket [] syntax is commonly used to access properties of objects dynamically (i.e., using a variable as the property name). This allows you to compute property names at runtime.*/
content_copyCOPY
Comments