Home > Software design >  How to add text on the last element of a map with react
How to add text on the last element of a map with react

Time:02-25

I have a array

const data = ["red", "green", "blue"];

and I would like to display it in a map in order to add a comma to it but also for the penultimate element the text "And".

To obtain the following display: "red", "green", and "blue".

I know the display that allows me to add the comma and the "".

  <div>
    {
      this.props.data.map(function(item, index) {
        return <span key={`${index}`}>{ (index ? ', "' : '"')   item }" 
</span>;
      })
    }
  </div>

but I don't know the solution to add the word "and" before the last element in case there are several.

Do you have a solution for this problem?

CodePudding user response:

Try this solution

  <div>
    {this.props.data.map(function (item, index) {
        if (index === this.props.data.length - 1)
          return (
            <span key={`${index}`}>
              {(index ? ', and "' : '"')   item}"
            </span>
          );
        return <span key={`${index}`}>{(index ? ', "' : '"')   item}"</span>;
      })}
  </div>

CodePudding user response:

Please try this solution I think it will help you out

{this.props.data.map(function (item, index) {
          return (
            <span key={`${index}`}>
              {index!==this.props.data.length-1? (index ? ', "' :
 '"')   item : (', and "' item)}"
            </span>
          );
        })}

CodePudding user response:

Based on @Borni.Mr answer.

<div>
 {["red", "blue", "green"].map(function (item, index) {
  if (index === ["red", "blue", "green"].length - 1)
   return <span key={`${index}`}>{` and "${item}"`}</span>;
  return <span key={`${index}`}>{(index ? ', "' : '"')   item}"</span>;
 })}
</div>

CodePudding user response:

Try this:

One way is using a ternary conditional for checking for the last item:

  <div>
    {
      this.props.data.map(function(item, index) {
        return <span key={`${index}`}>
{ (index === this.props.data.length-1) ? ', and "${item}' : ((index ? ', "' : '"')   item) }" 
               </span>;
      })
    }
  </div>
  • Related