我希望能够按照多列索引对多维数组进行排序。
例如,我有以下测试数据:
var source = [
["Jack","A","B1", 4],
["AVicky","M", "B2", 2],
["AVicky","F", "B3", 3],
];
我希望可以根据动态列索引对源进行排序,例如有时我想按照第一列+第二列进行排序,下一次可能会想按照第一列+第二列+第三列进行排序。
目前,我尝试了下面的代码,但它只能基于特定的列索引进行排序。
var source = [
["Jack","A","B1", 4],
["AVicky","M", "B2", 2],
["AVicky","F", "B3", 3],
];
var target = [
["Tom","M", "B3", 2],
["Jack","F", "B1", 1],
["Cindy","F", "B3", 3],
];
var keyIndexs = [0,1];
var same = [];
//order rows
var sourceOrder = source
keyIndexs.forEach(i => sourceOrder = sortByColumn(sourceOrder, i)) ;
console.log(sourceOrder);
for(var i = 0; i < source.length; i ++){
//console.log(ContainsRow(source[i], target));
if(ContainsRow(source[i], target)){
same.push(source[i]);
}
}
console.log(same);
function CompareRow(source:any[], target:any[]):boolean{
return JSON.stringify(source) === JSON.stringify(target);
}
function ContainsRow(source:any[], target: any[][]):boolean{
for(var i = 0; i <target.length; i ++){
if(CompareRow(source, target[i])){
return true;
}
}
return false;
}
function sortByColumn(a, colIndex){
a.sort(sortFunction);
function sortFunction(a, b) {
if (a[colIndex] === b[colIndex]) {
return 0;
}
else {
return (a[colIndex] < b[colIndex]) ? -1 : 1;
}
}
return a;
}
sortCompareFn
转换为像我的sortByColumn
函数定义一样的函数定义? - Edward