Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip certain elements when using javascript map()

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.

like image 240
user3282276 Avatar asked Jul 27 '26 12:07

user3282276


2 Answers

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 :)

like image 99
winhowes Avatar answered Jul 30 '26 01:07

winhowes


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(...);
like image 45
Kootoopas Avatar answered Jul 30 '26 03:07

Kootoopas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!