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
  • 31,174
  • 5
  • 48
  • 73
Anand Somani
  • 801
  • 1
  • 6
  • 15

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
  • 376,160
  • 25
  • 347
  • 392
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
  • 28,700
  • 8
  • 66
  • 83
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
  • 24,354
  • 5
  • 48
  • 79