简体   繁体   中英

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!

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) 

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

您可以match而不是split然后搜索非换行符。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM