Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

Iterate over a multidimensional javascript array and create new array?

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.

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

Of course, I can do like this.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...