1

I have a react project with the home.jsx file where I create an array of JSON:

function Home() {
  const posts = [
    {
      id:1,
      title:"Point Break",
      year:"1992",
      category:["Action","Hold-up","Crime","Surfing","Cult Movie"],
      description:"The film features Reeves as an undercover FBI agent....",
      image: "/movies/1.png"
    },{..}
//etc..

Then in the return of the home function I render that list like that:

return (
posts.map(
          post=>(
            <div className="post" key={ post.id}>
              <div className="img">
              </div>
              <div className="content">
                <h1>{post.title}</h1>         
                <p>Category: 
                  {  
                    post.category.map( element =>( element+", "))
                  }</p>                  
                <p>{post.description}</p>                    
              </div>                 
            </div>
))}

The problem comes when I want to render the category key with its array, with a comma between the words but not the last, because there is no word after that The output looks like that

Output

I want to avoid the last comma in the image, but apparently I cannot create any logic in the return. How can I achieve this? Do I need to make a function outside the return?

I already tried something like that:

  const filterCommas = (list,listlength) => {
    var $i=0;
    var renderlist=""
    list.forEach(element => {
      if($i<=listlength-1){
        renderlist += element + ", "
      }
      $i+=1;
    });
    return filteredList;
  }

But I cannot call it from the return function. How can I filter the commas?

Andy McRae
  • 525
  • 7
  • 15
  • 1
    have you tried to use `slice` to remove the latest character? – Rohad Bokhar Aug 31 '23 at 09:56
  • 2
    simply `post.category.join(", ")` ? https://stackoverflow.com/a/39771183/13583510 – cmgchess Aug 31 '23 at 09:57
  • Hi thanks for the answer Rohad. I tried (post.category.map( element =>( element+", "))).slice(0,-1) but actually it cuts the last element of the list :(. Actually there is a nooed to be able to put logic inside the render to remove the comma XD. I m gonna try other options but thanks – Andy McRae Aug 31 '23 at 10:03
  • Ok thanks. Post.category.join is perfect :). Thanks – Andy McRae Aug 31 '23 at 10:05

1 Answers1

1

Ok so cmgchess (Thanks a lot :)) gave me the answer which is:

> post.category.join(", ") inside the return:

So I would have:

<p>
    Category: {  
        post.category.join(", ")
    }
</p>

Instead of:

<p>
    Category: {  
        post.category.map( element =>( element+", "))
    }
</p>

Thanks for that :).

Still if there are other methods, I would be glad to hear because sometimes there is a need to be able to filter some informations with some logic (maybe a variable or a loop somewhere). Thanks

Andy McRae
  • 525
  • 7
  • 15