How could i compine two array based on the index.
so what i have is three (or more) array with different sizes something like the following :
a ['x1' , 'x2', 'x3'];
b ['y1','y2']
c ['z1']
i want to create a开发者_运维技巧 string like the following :
x1,y1,z1 - x2,y2 - x3
any idea how the logic behind doing something like this?
Just because I like to be contrary (who'd a thunk it!), here's an alternative using plain for loops:
var data = [
['q1','q2'],
['x1', 'x2', 'x3'],
['y1', 'y2', 'y3', 'y4', 'y5'],
['z1']
];
var result = [];
for (var i=0, iLen=data.length; i<iLen; i++) {
temp = data[i];
for (var j=0, jLen=temp.length; j<jLen; j++) {
if (!result[j]) {
result.push([temp[j]]);
} else {
result[j].push(temp[j]);
}
}
}
alert(result.join(' - ')); // q1,x1,y1,z1 - q2,x2,y2 - x3,y3 - y4 - y5
If support for sparse arrays is required (i.e. with missing members or values of undefined or null or whatever), that's not too hard to implement.
var arrays = [a, b, c];
var groupings = [];
var idx = 0;
while (true) {
var items = [];
for (var i = 0; i < arrays.length; i++) {
if (arrays[i].length > idx) {
items.push(arrays[i][idx]);
}
}
if (!items.length)
break;
else
groupings.push(items.join(','));
idx++;
}
console.log(groupings.join(' - '));
Let's say you have an array of arrays of arbitrary number, then you can use code like this to iterate through them:
var data = [
['q1', 'q2'],
['x1', 'x2', 'x3'],
['y1', 'y2', 'y3', 'y4', 'y5'],
['z1']
];
var output = "";
var term, j = 0;
while (true) {
term = [];
for (var i = 0; i < data.length; i++) {
if (data[i].length > j) {
term.push(data[i][j]);
}
}
// if no more terms, then all arrays are exhausted
// so it's time to break out of the loop
if (term.length == 0) {
break;
}
if (output) {
output += " - ";
}
output += term.join(",");
j++;
}
alert(output);
And, a working example here: http://jsfiddle.net/jfriend00/fZKbp/
精彩评论