Samurai Jack
Samurai Jack

Reputation: 3135

Check if it is the last element in an array inside map() function

I have an array of strings and I want to print them on different lines.

I'm using <hr /> for this but as it is now in my code, it will put another break after the last string, fact that I want to avoid. Any ideas?

This is my code:

return myArray.map((text, index) => (
    <span key={index}>
        {myArray[index]}
        {<hr />}
    </span>
));

Upvotes: 10

Views: 21280

Answers (4)

giggi__
giggi__

Reputation: 1973

Wrap them in a pragraph and not in a span

return myArray.map((text, index) => (
    <p key={index}>
        {text}
    </p>
));

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can check if its last element by checking if there is next element arr[i + 1]

var arr = ['a', 'b', 'c']
var html = arr.map(function(e, i) {
  return `<span key="${i}">${e}</span>${arr[i+1] ? '<hr>' : ''}` 
})

document.body.innerHTML += html.join('')

Upvotes: 24

cнŝdk
cнŝdk

Reputation: 32145

You just need to check upon iterated index, if(index < (myArray.length-1)) :

return myArray.map((text, index) => (
    <span key={index}>
        {myArray[index]}
        if(index < (myArray.length-1))
          {<hr />}
    </span>
));

Upvotes: 0

Reski
Reski

Reputation: 179

myArray.map((text, index, {length}) => (
  /* ... your code ... */
  if(index + 1 === length){ //last element

  }
));
//{length} === myArray.length; third argument is an array

Upvotes: 11

Related Questions