Most of the examples that are shown, when we search for .reduce()
method, are simple ones like sum
, average
, ...
In this article, we can explore some real programming use-case encounters where .reduce()
method can be used.
Example-1
Flatten the below-given input in the format of provided output, so that it will be easy to display the details in UI.
### Input:
{
productId:'prd_123',
price:1499,
customInfo:[
{
'color':['green', 'red']
},
{
'category':'fashion'
}
]
}
โ
### Output:
{
productId:'prd_123',
price:1499,
color:['green', 'red'],
category:'fashion'
}
Here, we can use the .reduce
method to flatten the object.
### Code Snippet
const {customInfo, ...rest} = object;
const flattenObject = customInfo.reduce((acc, val) => {
return {...acc, ...val};
}, {});
console.log({...rest, ...flattenObject});
Example - 2
### Input
{
'productId': 'prd_123',
'name': 'iphone X',
'variants':[
{
'price':'$599',
'color': 'black'
},
{
'price':'$699',
'color': 'midnight-green'
}
]
}
### Output
[
{
productId: 'prd_123',
name: 'iphone X',
price: '$599',
color: 'black'
},
{
productId: 'prd_123',
name: 'iphone X',
price: '$699',
color: 'midnight-green'
}
];
Given an object which holds the details of multiple mobile variants, but in the form of a nested object. Now, we can use .reduce()
method to return an array of mobile variants, which will be easy to iterate over.
let {variants, ...rest} = object;
let output = variants.reduce((products, variant) => {
products.push({...rest, ...variant})
return products
}, [])
console.log(output)
Conclusion
The .reduce()
method allows us to do some pretty neat data manipulation. It is really handy when it comes to making data easier to work with, or easier to represent where it needs to be read by humans.
Top comments (0)