遍历多维javascript数组并创建新的数组? [英] Iterate over a multidimensional javascript array and create new array?

查看:41
本文介绍了遍历多维javascript数组并创建新的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些字符串数据的多维JavaScript数组.

I have a multidimensional JavaScript array with some string data.

var array = [];

array[0] = ["A","B","C"];  
array[1] = ["G","H"];  

我想将它们合并到一个新的数组中.

I want to merge these together into a new array.

第一个数组中的值1应该与数组2中的值1合并,依此类推.

Value 1 from the first array should merge with value 1 from array 2 and so on.

我当然可以这样.

var array2 = array[0][0] + array[1][0];

但是我没有数据,所以第一个数组可以容纳6个值,并且也可以有2个以上的数组.

But I don't the data so the first array could hold 6 values and there could also be more than 2 arrays.

有没有一种方法可以动态地迭代多维数组并创建一个新数组.

Is there a way to dynamically iterate over the multidimensional array and create a new array.

推荐答案

您可以使用

You can use Array#map and Array#join methods.

// iterate over multi diamensional array and
// generate array with first element of each nested array
var array2 = array.map(function(v){ 
   // retrieve the first element
   return v[0]; 
   // join them to convert into a string as your output
}).join('')

var array = [];

array[0] = ["A", "B", "C"];
array[1] = ["G", "H"];

var array2 = array.map(function(v) {
  return v[0];
}).join('')

console.log(array2);

如果要对所有索引执行相同操作,请使用

If you want to do the same with all index then use Array#reduce method.

var array = [];

array[0] = ["A", "B", "C"];
array[1] = ["G", "H"];

// iterate and reduce a single array
var array2 = array.reduce(function(arr, e) {
  // iterate over nested array 
  e.forEach(function(v, i) {
    // concatenate with the elements in parent array
    arr[i] = (arr[i] || '') + v;
  });
  return arr
  // set initial value as array
}, [])

console.log(array2);

这篇关于遍历多维javascript数组并创建新的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆