Reputation: 814
I have this function which is used to get the news of a selected category. The first if case test if the category is indeed in the category's array as well as if it's not of type 'All'
and then push the category's news into an getNewsByCategory
. The second if case test if the category is of type 'All' and push all the categories's new into getNewsByCategory
.
If you notice in the two if cases there is the same code and i want to optimize it please
getNewsByCategory(category) {
const getNewsByCategory = [];
if (this.newsCategory) {
this.newsCategory.forEach(element => {
if (element.category === category && category !== 'All') {
element.news.filter(n => {
getNewsByCategory.push(n);
});
} else if (category === 'All') {
element.news.filter(n => {
getNewsByCategory.push(n);
});
}
});
return getNewsByCategory;
}
}
Upvotes: 1
Views: 54
Reputation: 912
Give a try to the reduce function, and I think you're misusing the filter function since it should be used with a returned boolean in order to create a new array with only the values that match a condition.
Plus you can use the spread operator (...) in the push function in order to push all the element.news.
Anyway:
getNewsByCategory(category) {
if (this.newsCategory) {
return this.newsCategory.reduce(
(newsByCategory, element) => (element.category === category || category === 'All') && newsByCategory.push(...element.news),
[]
);
}
}
Upvotes: 1
Reputation: 8982
This is the combination of those two if
s:
if (element.category === category || category === 'All')
Upvotes: 2