I have no idea how to phrase this question. I would appreciate it if you could include a better way to phrase this in your answer. My question is; is there a way to write the following code in a single statement? The only real difference is one adds to featured projects if e.featured
is false. And the other adds to openSourceProjects if it is true. I feel like I am missing something obvious.
const featuredProjects = allProjects.map((e) => {
if (e.featured == true) {
return (
buildCard(e)
);
}
});
const openSourceProjects = allProjects.map((e) => {
if (e.featured == false) {
return (
buildCard(e)
);
}
});
This seems dirty and is bordering on code duplication which I would like to avoid.
3
Answers
You can merge the two functions into one by using a single "map()" method and an "if-else" statement to conditionally call the
buildCard()
function based on thefeatured
property of each project.Here’s an example:
A single map() method to loop over all the projects in the allProjects array. For each project, Check if the featured property is true or false. If it’s true, Call the
buildCard()
function and return its output. If it’s false, You can also call the buildCard() function and return its output.Note that in your original code, the featuredProjects and allProjects arrays are assigned the results of calling map() with a callback function that doesn’t return anything. This means that both arrays will contain only undefined values. In the example above, Use the return keyword to return the output of the buildCard() function, which will populate the projects array with the card components.
you can filter out the seperated in one reduce call. here is an example. you can push the
buildCard(curr)
can even use an array as the accumulator. more readable as deceze
♦ mentioned
You can create a simple utility function to help you avoid the duplication:
and use it like this:
Now it’s simple and readable.
(Note: The
Projects
type you would probably define more explicitly in real code, but not knowing the type I used thetypeof
operator to make it work in this example.)