Temperedsoul Temperedsoul - 1 month ago 14
Javascript Question

Split array elements containing carriage return

Start with an array of strings, some of which feature carriage returns:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];


What I want to do is get rid of the carriage return, splitting the string into as many elements as there are carriage returns +1:

["Saab","Volvo","BMW","Honda","Audi","Mazda"];


What I get with .split:

valArray.split("\n");
["Saab","Volvo",["BMW","Honda","Audi"],"Mazda"];


Any suggestions?

Answer

Map the items to arrays after splitting the carriage returns, then flatten the arrays by applying concat:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

var result = [].concat.apply([], valArray.map(function(item) {
  var items = item.split('\n');
  
  return items;
}));

console.log(result);

And another method without a loop:

var valArray = ["Saab","Volvo","BMW\nHonda\nAudi","Mazda"];

var result = valArray.join(',').split('\n').join(',').split(',');

console.log(result);