I am trying to extract the length of an array while mapping it.
Here is what happens:
First I have an array of objects. Each object has a key of posts where I store the posts for that object. My code takes all the posts from all the objects and maps them to a new array so that I can show all the posts from all the objects to the user on the front end.
I'd like to show only 10 posts at a time. So I put a .slice(0, page * 10)
- the variable page is controlled by a button at the bottom of the page. If the user hits the button, the page then increases the number of posts on the screen.
This all works great. BUT - I'd like to be able to count the total number of posts and only show the button when there are more posts available. Is there a way to extract the number of posts while still allowing it to map the results from this function below?
{
bandTypes === "all"
? allBands
.filter(band => {
if (showType !== 'Show Type') {
return band.showTypes.includes(showType)
} else {
return band
}
})
.reduce(
(allPosts, band) =>
allPosts.concat(
(band.youtube.length > 0 &&
band.bandBio !== "n/a" &&
band.bandGenre !== "n/a")
? band.posts.map((post) => ({ post, band }))
: []
),
[]
)
.sort((a, b) => new Date(b.post.date) - new Date(a.post.date))
.slice(0, page * 10)
.map(({ post, band }) => <div key={uuidv4()}>{convertPost(post, band)}</div>)
: null
}
It would be great if I could just put an anonymous function in there somewhere that sets the state to the length of the array.