I have an array of objects that I am currently filtering and mapping, like this:
const countries = [
"de",
"fr",
"nl"
];
const renderDocItem = (doc, country) => {
return (
<li className="tabsLi" key={doc._id}>
<div className="d-flex w-75 justify-content-between">
<div>
{doc.name}
<br />
<span className="filename">{doc.filename}</span>
</div>
<div>
{doc.master ? (
<img className="flag" src={en} />
) : (
<img
className="flag"
src={objectOfCountries[country]}
/>
)}
<span className="action">
[
<a href="#" onClick={() => view(doc, "view")}>
view
</a>
,{" "}
<a href="#" onClick={() => view(doc, "edit")}>
edit
</a>
]
</span>
</div>
</div>
</li>
);
};
const renderDocsPerCountry = (docs, country, category) => {
const filteredDocs = docs.filter((doc) => {
return doc.countries.includes(country) && doc.category == category;
});
const renderedDocs = filteredDocs.map((doc) => {
return renderDocItem(doc, country);
});
console.log(renderedDocs);
return renderedDocs;
};
<ul>{renderDocsPerCountry(docs, country, "xxx")}</ul>
This creates a list of items, filtered by "xxx" and grouped per country.
The problem I have is that some of the items, have the same name property, but different country. I want to be able to group the items with same name.
Current output:
- Name1, filename1, country1, link
- Name1, filename2, country2, link
- Name3, filename3, country3, link
Desired output:
- Name1, filename1/filename2, country 1 – link / country 2 – link
- Name3, filename3, country3, link
How would the reduce function look like?
3
Answers
I could use the map function with JS arrays and maps.
Here is some pseudo code:
The map value will be arrays of items with the same name.
Ps: I did not use reduce but achieved the objective of grouping items based on name.
If you want to group items with the same name but different countries, you can use the reduce() function. First, you can use reduce() to create an object that groups the items by name. Then, you can use Object.entries() to iterate over the object and create an array of the grouped items.