As we can create a object with some properties as follows:
let obj = {};
obj.pp1 = "abc";
obj.pp2 = 1;
Now the object will have properties pp1 and pp2.
Now I am using the same pattern inside a reduce()
function to summarize the basket contents as follows:
Approach 1:
const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];
const aggregatedBasket = fruitBasket.reduce(
(ag , item) => {
if (ag.hasOwnProperty(item) == false){
ag.item. = 1;
} else {
ag.item += 1;
}
return ag;
}, {});
console.log(aggregatedBasket);
But when I run the code, it is returning output as:
{ item: 1 }
I know it is wrong as output is not correct, now I tried the following pattern
Approach 2:
const aggregatedBasket = fruitBasket.reduce(
(ag , item) => {
if (ag.hasOwnProperty(item) == false){
ag[item] = 1;
} else {
ag[item] += 1;
}
return ag;
}, {});
console.log(aggregatedBasket);
Now it is printing the correct output, But I am unable to understand why .
operator is failing in Approach 1.
Note: I am a beginner in JavaScript, please help me to understand. It might look simple to many experts there.