简体   繁体   English

如何将两个数组压缩为一个包含值的字符串数组

[英]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.

相关问题 如何从一个包含对象的大型阵列中获得两个分离的 arrays? - how do I get two separated arrays from on one large array containing obejcts? 我如何在 JavaScript 中使用 zip 两个 arrays? - How do I zip two arrays in JavaScript? 如何合并两个数组以在JavaScript中创建一个数组? - How do I merge two arrays to create one array in JavaScript? 如何从一个对象创建一个字符串数组,其中各个键的值是单独的字符串数组? - How do I create an array of strings from an object where the values of individual keys are separate arrays of strings? 如何在 JavaScript 中比较两个包含字符串的变量? - How do I compare two variables containing strings in JavaScript? 将两个包含数组的对象串联到一个包含对象的数组中 - concatenate two objects containing arrays in to one array containing objects 如何将 zip 两个 arrays 放入一个阵列中,每个阵列包含另一个阵列 - How to zip two arrays into one array which every array contains another array 如何将数组转换为数组 object 并将两个 arrays 合并为一个数组? - How do I convert array to an array object and combine two arrays to a one array? 如何使用两个单独的数组执行操作,一个数组包含值,另一个数组包含操作数 - How do perform operation with two separate arrays one containing the value and another containing the operand 如何将包含多个js语句的字符串拆分为字符串数组,每个字符串包含一个语句? - How can I split a string containing multiple js statements into an array of strings each string containing one statement?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM