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"]
Lodash proves to be much useful when working with arrays, strings, objects etc. It makes math operations and function paradigm much easier, concise. The _. concat() function is used to concatenating the arrays in JavaScript.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
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);
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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With