我在数组中有N个数组,现在N = 3
[[1,2,3, "a","b"] , [3,4,5,"c"], [6,7,8]...]
我想让它返回
[[1,3,6], [2,4,7], [3,5,8], ...., ["a","c", ""], ["b", "",""]]
有很多组合两个数组的解决方案,但我想处理任意数量的数组。我想让它回到上面。我希望在没有下划线或jquery的情况下这样做。
Values=[];
status = [[1,2,3, "a","b"] , [3,4,5,"c"], [6,7,8]];
status_name = status[0]; //take the longest one always
for (i = 0; i < status_name.length; ++i)
{
Values[i] =Array(status_name[i], status[i+1][i]);
}
答案 0 :(得分:0)
从概念上讲,使用嵌套循环最容易实现;
var a = [[1, 2, 'x'], ['a', 'b'], ['+', '-', 'y', 'z']]; // input array
function transform(a) {
var i, j, // two loops = two variables to iterate with
foundSomething, // a flag so we know to stop
b = []; // output array
i = 0;
do { // loop for i
foundSomething = false;
b[i] = [];
for (j = 0; j < a.length; ++j) { // loop for j
if (i in a[j]) { // something exists at this level of i
foundSomething = true;
b[i].push(a[j][i]);
} else { // nothing here
b[i].push(''); // insert empty string
}
}
++i;
} while (foundSomething);
b.length = b.length - 1; // snip empty end
return b;
}
transform(a); // [[1, "a", "+"], [2, "b", "-"], ["x", "", "y"], ["", "", "z"]]
需要排序吗?
a.sort(function (a, b) {return a.length < b.length;}); // bigger arrays first
transform(a); // [["+", 1, "a"], ["-", 2, "b"], ["y", "x", ""], ["z", "", ""]]
如果你总是这样做,你可以进一步优化transform
,即因为你知道所有a[x].length >= a[y].length
x < y
,你不需要标记你是否找到了什么
答案 1 :(得分:0)
为什么不嵌套循环?
某物。像这个警告伪代码
Values=[];
status = [[1,2,3, "a","b"] , [3,4,5,"c"], [6,7,8];
status_name = status[0];
for (i = 0; i < status.length; ++i)
{
for (k = 0; k < status[i].length; ++i)
{
Values[i] =Array(status[i][k], status[k+1][k]);
}
}
答案 2 :(得分:0)
var originalArray = [[1, 2, 3, "a", "b"], [3, 4, 5, "c"], [6, 7, 8]];
var theValues = new Array();
var actualArray = originalArray.pop();
var maxLength = originalArray.length;
while (actualArray) {
for (var i = 0; i < actualArray.length; i++){
var newArray = theValues[i];
if (!newArray) {
theValues[i] = new Array();
}
theValues[i].push(actualArray[i])
}
actualArray = originalArray.pop();
}
for (var i = 0; i < theValues.length; i++) {
for (var j = maxLength - theValues[i].length; j >= 0; j--) {
theValues[i].push("");
}
}