[英]How do I zip two arrays into one array of strings containing the values
For instance, if I have two arrays that look like this: 例如,如果我有两个看起来像这样的数组:
var array1 = ['a','b'];
var array2 = [1, 1];
The output array should be: 输出数组应该是:
var newArray = ['a:1', 'b:1']
You could use map
like this: 您可以像这样使用map
:
var array1 = ['a','b'], array2 = [1, 1]; var newArray = array1.map((e, i) => `${e}:${array2[i]}`); console.log(newArray);
You could map the value of the iterating array and from the other array the value of the actual index. 您可以映射迭代数组的值,并从另一个数组映射实际索引的值。
var array1 = ['a', 'b'], array2 = [1, 1], result = array1.map((a, i) => [a, array2[i]].join(':')); console.log(result);
The same with an arbitrary count of arrays 与任意数组的数组相同
var array1 = ['a', 'b'], array2 = [1, 1], result = [array1, array2].reduce((a, b) => a.map((v, i) => v + ':' + b[i])); console.log(result);
If you are willing to use lodash you can do this very easily with zipWith
. 如果您愿意使用lodash,可以使用zipWith轻松zipWith
。 It takes arrays and combines the values grouped by index according to a function you provide: 它需要数组并根据您提供的函数组合按索引分组的值:
var newArr = lodash.zipWith(array1, array2, (arr1val, arr2val) => `${arr1val}:${arr2val}`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.