I’m trying to understand the .reduce()
function and the best way to go about the following.
I’ve got the following code:
JavaScript
x
12
12
1
const products = [
2
{ name: 'apples', category: 'fruits' },
3
{ name: 'oranges', category: 'fruits' },
4
{ name: 'potatoes', category: 'vegetables' }
5
];
6
7
const groupByCategory = products.reduce((group, product) => {
8
const { category } = product;
9
group[category] = group[category] ?? [];
10
group[category].push(product);
11
return group;
12
}, {});
I want to add a product with no ‘category’ property in it, and I want it pushed into a specific key rather than getting grouped in “undefined”, so I edited it to:
JavaScript
1
24
24
1
const products = [
2
{ name: "apples", category: "fruits" },
3
{ name: "oranges", category: "fruits" },
4
{ name: "potatoes", category: "vegetables" },
5
{ name: "guava"}
6
];
7
8
const groupByCategory = products.reduce((group, product) => {
9
10
const { category } = product ;
11
12
// check if 'category' exists, if it doesn't store it as an empty array to push to
13
group[category] = group[category] ?? [];
14
15
// if category is undefined, push it into 'nocategory'. Otherwise push into relevant.
16
if(!category){
17
group['nocategory'].push(product);
18
} else {
19
group[category].push(product);
20
};
21
return group;
22
}, {'nocategory':[]});
23
24
console.log(JSON.stringify(groupByCategory, null, 2));
For the most part it works (there’s still an ‘undefined’ group, but at least the object gets pushed into the right group).
I’m sure there’s a better solution/proper way to do this. Any pointers would be appreciated.
Advertisement
Answer
Instead of a whole new conditional block you could just set a default in the destructuring and then group as usual.
JavaScript
1
2
1
const { category = 'nocategory' } = product;
2
JavaScript
1
17
17
1
const products = [
2
{ name: "apples", category: "fruits" },
3
{ name: "oranges", category: "fruits" },
4
{ name: "potatoes", category: "vegetables" },
5
{ name: "guava"}
6
];
7
8
const groupByCategory = products.reduce((group, product) => {
9
10
const { category = 'nocategory' } = product;
11
group[category] ??= [];
12
group[category].push(product);
13
14
return group;
15
}, {});
16
17
console.log(JSON.stringify(groupByCategory, null, 2));
Note: you can also make use of logical nullish assignment (??=)