我有一个按编号排序的数组列表,按行显示X项。
data.people.sort(function (a, b) {
return a.grade - b.grade;
});
数组中的每个项目都有两个数字。当前网格按第一个数字排序(按行)。现在,我想用第二个数字(垂直)对每列的结果进行排序。
答案 0 :(得分:1)
尝试
function custom_sort (_arr, columnCount) {
var cols,c,arr2,arr = _arr.sort(function (a, b) {
return a.grade - b.grade;
});
cols = [];
for(c = 0; c < columnCount-1; c+=1) {
cols.push([]);
}
arr.forEach(function (e,i) {
var c = i%columnCount;
cols[c].push(arr[i]);
});
cols.map(function (e,i) {
return cols[c].sort(function (a, b) {
return a.otherVal - b.otherVal;
});
});
for(var i = 0; i < arr.length; i+=1){
var c = i%columnCount, l = Math.floor(i/columnCount);
arr2.push(cols[c][l]);
}
return arr2;
}
...
custom_sort(data.people, 5);
答案 1 :(得分:1)
这是一种基于任意行长度的排序。
// Your array here.
var arr = [
{first: 1, second: 5},{first: 2, second: 1},{first: 3, second: 6},
{first: 4, second: 2},{first: 5, second: 2},{first: 6, second: 3},
{first: 7, second: 3}
];
// Your row length here.
var rowLen = 3;
//////////////////////////////////////////////////
var colLen = Math.ceil(arr.length / rowLen);
console.log("original");
showArr(arr, rowLen);
for(var curCol = 0; curCol < rowLen; curCol++)
{
// Standard insertion sort on colums.
for(var i = 0; i < colLen - 1; i++)
{
for(var j = i + 1; j < colLen; j++)
{
if(j * rowLen + curCol < arr.length)
{
var colIdxI = i * rowLen + curCol;
var colIdxJ = j * rowLen + curCol;
if(comparitor(arr[colIdxI].second, arr[colIdxJ].second) == 1)
{
// Swap.
var temp = arr[colIdxI];
arr[colIdxI] = arr[colIdxJ];
arr[colIdxJ] = temp;
}
}
}
}
}
console.log("sorted");
showArr(arr, rowLen);
function comparitor(a, b)
{
if (a < b)
{
return -1;
}
if (a > b)
{
return 1;
}
else
{
return 0;
}
}
function showArr(arr, rowLen)
{
var set;
for(var i = 0; i < arr.length; i++)
{
if(i % rowLen == 0)
{
console.log(set);
set = "";
}
set += JSON.stringify(arr[i]) + " ";
}
if(arr.length % rowLen != 0)
{
console.log(set);
}
}