将两个数据阵列组合并修改为单个阵列

时间:2014-04-11 10:50:41

标签: javascript html arrays

考虑这个jsfiddle示例。在这个例子中,我想要var数据数组

[4,3],
[4,4],
[6, 6],
[6, 7],
[7,8],
[7,9],
[8,10],
[8,11]

将被修改为

 [4,3,4],
 [6,6,7],
 [7,8,9],
 [8,10,11]

我想将[X,Y]字段修改为[X,Y1,Y2]。怎么做?

2 个答案:

答案 0 :(得分:2)

//Original data
var data = [[4,3],
[4,4],
[6, 6],
[6, 7],
[7,8],
[7,9],
[8,10],
[8,11]]

//Group data by x coordinate in an object
var intermediate = {};

for(var i = 0; i < data.length; i++){
    intermediate [data[i][0]] = (intermediate [data[i][0]] || []).concat(data[i][1]);
}

//Convert intermediate object to array
var result = [];

for(var i in intermediate){
        result.push([parseInt(i)].concat(intermediate[i]));
}

编辑以相反的方式更改数据:

var data = [[4,3,4],[6,6,7],[7,8,9],[8,10,11]];
var result = [];

data.forEach(function(row){
    row.slice(1).forEach(function(cell){
        result.push([row[0], cell]);
    });
});

答案 1 :(得分:1)

var result = [];
var arr = [[4,3], [4,4],[6, 6],[6, 7],[7,8],[7,9],[8,10],[8,11]];
for(var i = 0;i< arr.length;i+=2){
    result.push([arr[i][0], arr[i][1], arr[i+1][1]])
}