7

Input:

var array1 = ["12346","12347\n12348","12349"];

Steps:

Replace \n with ',' and Add into list.

Output:

var array2 = ["12346","12347","12348","12349"];

I tried below logic but not reach to output. Looks like something is missing.

var array2 = [];

_.forEach(array1, function (item) {               
       var splitData = _.replace(item, /\s+/g, ',').split(',').join();
       array2.push(splitData);
});

Output of my code:

["12346","12347,12348","12349"]
ibrahim mahrir
  • 29,774
  • 5
  • 43
  • 68
Anand Somani
  • 777
  • 1
  • 5
  • 14

3 Answers3

10

You could join it with newline '\n' and split it by newline for the result.

var array= ["12346", "12347\n12348", "12349"],
    result = array.join('\n').split('\n');

console.log(result);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
3

If you're using lodash, applying flatmap would be the simplest way:

var array1 = ["12346", "12347\n12348", "12349"];
var array2 = _.flatMap(array1, (e) => e.split('\n'));

console.log(array2);
//=> ["12346", "12347", "12348", "12349"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
ntalbs
  • 27,110
  • 8
  • 61
  • 81
1

An alternate to @Nina's answer would be to use Array.push.apply with string.split(/\n/)

var array= ["12346","12347\n12348","12349"];
var result = []

array.forEach(function(item){
   result.push.apply(result, item.split(/\n/))
})

console.log(result);
Rajesh
  • 22,581
  • 5
  • 41
  • 70