Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat array into one array (JS or Lodash)

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"]
like image 875
Anand Somani Avatar asked Feb 22 '17 12:02

Anand Somani


People also ask

How do I merge arrays in Lodash?

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.

Can we concat two 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.

How do I combine two 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.

Can we concat two arrays?

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.


Video Answer


3 Answers

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);
like image 199
Nina Scholz Avatar answered Oct 12 '22 04:10

Nina Scholz


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>
like image 31
ntalbs Avatar answered Oct 12 '22 03:10

ntalbs


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);
like image 34
Rajesh Avatar answered Oct 12 '22 02:10

Rajesh