[英]Concat array into one array (JS or Lodash)
Input: 输入:
var array1 = ["12346","12347\n12348","12349"];
Steps: 脚步:
Replace
\\n
with','
and Add into list. 将\\n
替换为','
并添加到列表中。
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"]
You could join it with newline '\\n'
and split it by newline for the result. 你可以用换行符'\\n'
加入它,然后用换行符将它拆分为结果。
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: 如果你正在使用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>
An alternate to @Nina's answer would be to use Array.push.apply
with string.split(/\\n/)
@ 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.