I currently have this bit of code to split up a string and display it as a list.
<span className="reply">{this.props.message.split("\n").map((chunk) => {
return <span className="message-chunk">{chunk}<br /></span>
})}
I want to skip the first and last element in the split array because the string is of the form.
Heading\n
List Item\n
List Item\n
List Item\n
Ending\n
Is there a way to do this while using the map function. I saw mention of the filter() function in another related question but I don't think that's applicable here. Any help is appreciated.
One option is to just slice the array before you map, so in your case it would be:
this.props.message.split("\n").slice(1, -1).map((chunk) => {
return <span className="message-chunk">{chunk}<br /></span>
})
Note that this will remove the first and last element from the array. If you are intending to not modify the first or last element I recommend @vlaz's answer :)
A pretty clean solution would be to store the line separated array. Then .shift() and .pop() it to trim edges (and store them if you need to), and iterate the trimmed array with .map(). :)
// Example with stored heading and ending
let messageLines = this.props.message.split("\n");
const heading = messageLines.shift();
const ending = messageLines.pop();
// Map whenever you need to
messageLines.map(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With