0

I got the excise on JS as below:

Finish the function group. Sort each food by it's type and return an object in the format shown below example.

Given an array of fruits in this format:

[
    { food: 'apple', type: 'fruit' }, 
    { food: 'orange', type: 'fruit' }, 
    { food: 'carrot', type: 'vegetable' }
]
Let's turn it into an object with this format:

{ 
     fruit: ['orange', 'apple'], 
     vegetable: ['carrot'] 
}

Correct answer is below codes:

// food is an array full of food objects
// let's group them by "type" and return them
function group(foods) {
    return foods.reduce((accumulator, currentValue) => {
        accumulator[currentValue.type] = accumulator[currentValue.type] || []
        accumulator[currentValue.type].push(currentValue.food);
        return accumulator;
    }, {});
}

module.exports = group;

My question is, since the initial value for accumulator is a empty object {}, and we plan to add new values to this Object. But why use the line like this "accumulator[currentValue.type].push(currentValue.food);", I thought it should push a value to array when it is written like this "accumulator[currentValue.type]", why it didn't be written like "accumulator.currentValue.type"? should it be the way how to access the value in Object? Could you explain why I am wrong?

Thanks,

0 Answers0