简体   繁体   English

在 JavaScript 中明智地展平数组元素

[英]Flatten An array element wise in JavaScript

I have two Arrays which look like this:我有两个 Arrays 看起来像这样:

array1: [["abc","def","ghi"],["jkl","mno","pqr"]],
array2: [[1,2,3,4,5],[6,7,8,9,10]]

I want to operate a Flattening operation which gives me result like this: Flatten(array1,array2) :我想执行一个 Flattening 操作,它给我这样的结果: Flatten(array1,array2)

result: [["abc","def","ghi",1,2,3,4,5],["jkl","mno","pqr",6,7,8,9,10]]

Any suggestions on the same?有什么建议吗?

Edit 1: Both the Arrays always have the same length.编辑 1: Arrays 的长度始终相同。

You can use map() on one of them and concat() it with corresponding element of other array您可以在其中一个上使用map()并将其与其他数组的相应元素一起使用concat()

Note: I am considering length of both the arrays will be equal注意:我正在考虑 arrays 的长度相等

 const arr1 = [["abc","def","ghi"],["jkl","mno","pqr"]]; const arr2 = [[1,2,3,4,5],[6,7,8,9,10]]; const flattern = (a1, a2) => a1.map((x, i) => x.concat(a2[i])) console.log(flattern(arr1, arr2))

If lengths of arrays are not same then you will have to first find the larger array and then map over it.如果 arrays 的长度不相同,那么您必须先找到较大的数组,然后再找到 map。

 const arr1 = [["abc","def","ghi"],["jkl","mno","pqr"], ['a','b','c']]; const arr2 = [[1,2,3,4,5],[6,7,8,9,10]]; const flattern = (a1, a2) =>{ if(a1.length === a2.length){ return a1.map((x, i) => x.concat(a2[i])) } else if(a1.length > a2.length){ return a1.map((x, i) => x.concat(a2[i] || [])) } else{ return a2.map((x, i) => x.concat(a1[i] || [])) } } console.log(flattern(arr1, arr2))

Since the length of the array is same, you could use map() over one array and concat the other.由于数组的长度相同,您可以在一个数组上使用map()concat另一个数组。

 const array1 = [["abc","def","ghi"],["jkl","mno","pqr"]]; const array2 = [[1,2,3,4,5],[6,7,8,9,10]]; let result = array1.map((a, i) => a.concat(array2[i])); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM