我在javascript中有一个多数组对象
[["A","F","A","H","F","F"],["F","A","A","F","F","H"]]
我想使用一些排序算法
获得以下内容[["A","A","A","H","A","F"],["F","F","F","F","F","H"]]
“A”和“F”中不的字母应保持在其数组的相同位置。只应对“A”和“F”进行排序。
答案 0 :(得分:1)
你可以展平你的数组,对它进行排序,使每个A都在F之前,然后再次切片以匹配原始数据的结构。
var data = [["A","F","A","H","F","F"],["F","A","A","F","F","H"]]
function custom_sort(data) {
var sort = [].concat(...data.slice()), r = []
sort.forEach(function(e, i) {
if (e == 'A') {
var fi = sort.indexOf('F')
if (fi < i)(sort[fi] = 'A', sort[i] = 'F')
}
})
data.forEach(e => r.push(sort.splice(0, e.length)))
return r
}
console.log(JSON.stringify(custom_sort(data)))
console.log(JSON.stringify(custom_sort( [["F","F","A","H","F"],["F", "Z", "I", "A","A","A","F","H", "A"]])))
&#13;
答案 1 :(得分:0)
检查一下。 只需运行此代码。
function sortIt(a){
var i=0,j=0;
while(i<a.length){
j=i;
while(j<a.length){
if((a[i]=="F" || a[i]=="A") && (a[j]=="F" || a[j]=="A") && a[i].charCodeAt(0)>a[j].charCodeAt(0)){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
j++;
}
i++;
}
return a;
}
function splitUp(a){
var b=[],i=0;
while(i<a.length){
b.push(sortIt(a[i]));
i++;
}
return b;
}
//test
var c=[['A','F','F','H','B','A','A','F','Z','X'],['F','A','A','F','F']];
console.log("Before Sorting\n");
console.log(c);
c = splitUp(c);
console.log("After sorting");
console.log(c);
&#13;
答案 2 :(得分:0)
您可以使用传统方法过滤不可移动的项目并对其余项目进行排序,并将不可移动的项目拼接到原始位置。
function sort(array) {
var solid = [],
sortable = { A: true, F: true },
i = array.length;
while (i--) {
sortable[array[i]] || solid.unshift({ index: i, value: array.splice(i, 1)[0] });
}
array.sort(function (a, b) {
return a.localeCompare(b);
});
solid.forEach(function (a) {
array.splice(a.index, 0, a.value);
});
}
var array = [["A", "F", "A", "H", "F", "F"], ["F", "A", "A", "F", "F", "H"]],
temp = array[0].concat(array[1]);
sort(temp);
array = [temp.slice(0, 6), temp.slice(6, 12)];
console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 3 :(得分:0)
var myArrays = [["A","F","A","H","F","F"],["F","A","A","F","F","H"]];
var lengths = [];
var tempArray = [];
var sortArray = [];
var noSortArray = [];
myArrays.forEach(function(arr) {
lengths.push(arr.length);
tempArray = tempArray.concat(arr);
});
tempArray.forEach(function(item, index) {
if (item === 'H') {
noSortArray.push({index: index, item: item});
} else {
sortArray.push(item);
}
});
sortArray.sort();
noSortArray.forEach(function(item) {
sortArray.splice(item.index, 0, item.item);
});
var position = 0;
var theLength = 0;
myArrays = [];
lengths.forEach(function(aLength) {
theLength += aLength;
myArrays.push(sortArray.slice(position, theLength));
position += aLength;
console.log(position);
});
console.log(myArrays);
&#13;