2

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.

3
  • Do you mean "skip" as in still return the heading and end but transform everything else, or only return the list items? Commented Sep 10, 2016 at 21:37
  • @vlaz I mean the first Commented Sep 10, 2016 at 22:01
  • @user3282276 If one of the answers is correct please mark it as so. If none of them are please provide feedback as to how it does not solve your issue. Thanks Commented Sep 11, 2016 at 21:22

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

slice doesn't mutate the array, but returns a new one, so this is the best answer.
1

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(...);

Comments

1

The callback function for Array.prototype.map will be passed three parameters - the element, the index, and the array. So you can very easily skip the first and last element when transforming

arr.map(function(item, index, list) {
    if(index === 0 || index === list.length -1) {
         return item;
    } else {
        /* transformation logic */
        return transformedItem;
    }

})

2 Comments

The problem with this is that the first and last element are still in the returned array
OP said skip them which I took to mean they still need to be returned. Perhaps the requirement is to remove them but it's not totally clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.