如何在javascript中对多维数组进行排序
how to sort this multi dimensional array in javascript
var arr = [];
arr[0] = [{id:1}, {id:5}, {id:7}];
arr[1] = [{id:3}, {id:8}, {id:6}];
arr[2] = [{id:2}, {id:4}, {id:9}];
The output should be like this
arr[0] = [{id:1}, {id:2}, {id:3}];
arr[1] = [{id:4}, {id:5}, {id:6}];
arr[2] = [{id:7}, {id:8}, {id:9}];
答案 0 :(得分:1)
我能想到的最简单的解决方案是:
var sortChunks = function(ar, property,chunkSize)
{
//set default params:
chunkSize = chunkSize || ar[0].length;// || 3?;
property = property || 'id';
var i=0,j=0,all = [],ret = [];
for(i=0;i<ar.length;i++)
{//"map" objects, use property as array index
for(j=0;j<ar[i].length;j++)
{
all[ar[i][j][property]] = ar[i][j];
}
}
all.sort(function(a,b)
{//move all undefined keys to the end of the array
if (a === undefined)
return 1;
if (b === undefined || b.id > a.id)
return -1;
else
return 1;
});
while(all && all[0] !== undefined)
{//make chunks
ret.push(all.splice(0,chunkSize));
}
return ret;
};
//usage:
arr = sortChunks(arr);//returns desired array
//or
arr = sortChunks(arr,'id',3);
话虽如此,你可能更好地重新思考这个数组的构建方式,并改变那些代码,而不是依赖于这种相当多的(并且当前形式相当容易出错)排序功能。
与此同时,check this fiddle看到它在行动......有点
答案 1 :(得分:1)
您需要一些辅助功能:
Array.prototype.flattened = function() {
return Array.prototype.concat.apply([], this);
};
Array.prototype.splitBy = function(n) {
var r = [];
for (var i=0; i<this.length; i+=n)
r.push(this.slice(i, i+n));
return r;
};
Array.prototype.sortBy = function sortBy(key) {
if (this[0] && this[0][key] == "number")
return this.sort(function(a,b) {return a[key] - b[key];});
return this.sort(function(a, b) {
return a[key]<b[key] ? -1 : a[key]>b[key] ? 1 : 0;
});
};
然后,很容易:
arr.flattened().sortBy("id").splitBy(3);
答案 2 :(得分:0)
您可以使用n * m个元素创建“1维”数组。其中n和m是行数和列数。然后使用排序算法之一。