Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
));
like image 691
Samurai Jack Avatar asked Jun 20 '17 10:06

Samurai Jack


2 Answers

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('')
like image 86
Nenad Vracar Avatar answered Sep 18 '22 17:09

Nenad Vracar


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

  }
));
//{length} === myArray.length; third argument is an array
like image 43
Reski Avatar answered Sep 19 '22 17:09

Reski