I will use this example http://codepen.io/lacker/pen/vXpAgj , since it's very similar to my current issue. So, let's say we have this array:
[
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
{category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
]
How can I rewrite the code below using array.map()?
var rows = [];
var lastCategory = null;
this.props.products.forEach(function(product) {
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
The sample below doesn't do the job properly.
const lastCategory = null;
const rows = this.props.products.map(function(product){
if (product.category !== lastCategory) {
return (<ProductCategoryRow category={product.category} key={product.category} />);
}
return (<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
Cheers and thank you,
lastCategory = product.categoryline due to the return above it