Concat数组成一个数组(JS或Lodash)

时间:2017-02-22 12:24:38

标签: javascript lodash

输入:

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

步骤:

  

\n替换为','并添加到列表中。

输出:

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

我尝试了以下逻辑,但未达到输出。看起来有些东西不见了。

var array2 = [];

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

输出我的代码:

["12346","12347,12348","12349"]

3 个答案:

答案 0 :(得分:10)

您可以使用换行符'\n'将其加入,然后按换行符换行。



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

console.log(result);




答案 1 :(得分:3)

如果你正在使用lodash,那么应用flatmap将是最简单的方法:



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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

@ Nina答案的替代方法是Array.push.apply使用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);