Aly Dabbous
Aly Dabbous

Reputation: 107

splitting an array with one item into an array with many items

I have an array that returns the following item:

["\nOnprogress\nDone"]

I want to turn it into an array that splits this item into two items like this:

["Onprogress" , "Done"]

I also want to remove the unnecessary '\n' characters without removing the 'n' characters from the words themselves. As demonstrated above ^. Any ideas how to do that?

This is my code:

    addCardtoApp = event => {
        event.preventDefault();
        const card = {
            taskName: this.taskName.current.value, 
            taskDescription: this.taskDescription.current.value,
            taskPeriod: this.taskPeriod.current.value,
        };
        const cardStatus = this.taskStatus.current.value;
        let otherStatus = {
            otherStatus: this.taskStatus.current.innerText,
        };
        const replacedStatus = otherStatus.otherStatus.replace(`${cardStatus}`, '');
        const convertedStatus = replacedStatus.split(" ");
        const refinedStatus = JSON.stringify(convertedStatus).replace(/↵/, '');
        console.log(refinedStatus);
        this.props.addCard(card, cardStatus, replacedStatus);
        event.currentTarget.reset();
    };

Thanks in advance!

Upvotes: 0

Views: 68

Answers (3)

Ori Drori
Ori Drori

Reputation: 191976

Use Array.flatMap() and split the string. Then filter out empty items:

const arr = ["\nOnprogress\nDone"]

const result = arr
  .flatMap(str => str.split('\n'))
  .filter(Boolean) // or .filter(s => s.length > 0) for the sake of readability

console.log(result)

And if flatMap is not supported, you can use Array.map(), spread, and Array.concat():

const arr = ["\nOnprogress\nDone"]

const result = [].concat(...arr.map(str => str.split('\n')))
  .filter(Boolean) // or .filter(s => s.length > 0) for the sake of readability

console.log(result)

Upvotes: 2

ellipsis
ellipsis

Reputation: 12152

Use split and splice

var a=["\nOnprogress\nDone"]
var arr=a.map(e=>e.split("\n")[0]==""?e.split("\n").splice(1):e.split("\n"))
console.log(arr.flat(1))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

You could take match instead of split and search for non linefeed characters.

console.log("\nOnprogress\nDone".match(/[^\n]+/g));

Upvotes: 0

Related Questions