Could someone please explain how reduce() is counting the instances of an array item and adding them to the empty object in the below code? For example, we end up with { car: 5, truck: 3 }. I don't quite understand what obj[item] is.
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const transportation = data.reduce(function(obj, item) {
if (!obj[item]) {
obj[item] = 0;
}
obj[item]++;
return obj;
}, {});
console.log(transportation);//{car: 5, truck: 3, bike: 2, walk: 2, van: 2}
objis? If not check documentation howreduceworks. In any case feel free to use debugging technics: putconsole.log(obj)on top of the callback and you will understand how everything works.item==='car',obj[item]isobj['car']orobj.car- does that help?obj[item]is referencing an element of theobjobject which is named after the current, iterative value passed to the callback. So it might translate asobj['car'], for example.