我接收陣列是這樣的:JavaScript - 如何通過數字字符串對數組進行排序?
[
[{"name":"one","team":"------","checked":false,"position":"-"},
{"name":"two","team":"------","checked":false,"position":"1"}],
[{"name":"three","team":"------","checked":false,"position":"3"},
{"name":"four","team":"------","checked":false,"position":"7"}]
]
我想要的最終輸出是這樣的:
[
[{"name":"two","team":"------","checked":false,"position":"1"},
{"name":"four","team":"------","checked":false,"position":"7"}],
[{"name":"three","team":"------","checked":false,"position":"3"},
{"name":"one","team":"------","checked":false,"position":"-"}]
]
這意味着,該陣列是由最大位置值和所述至少位置值排序在第一子陣列中,然後是第二子陣列中的第二最大位置值和第二最小位置值。如果在位置上有一個「 - 」,它將留在字符串編號之後。
到目前爲止,我已經與lodash試過這樣:
var mergedArray = vm.roundOf4[0].concat(vm.roundOf4[1]);
var count = _.countBy(mergedArray, {position: '-'});
var ascArray = _.cloneDeep(mergedArray);
var descArray = _.cloneDeep(mergedArray);
_.sortByOrder(ascArray, 'position', 'asc');
_.sortByOrder(descArray, 'position', 'desc');
_.times(count.true, ascArray.push(ascArray.shift()));
vm.roundOf4.some(function (array, i) {
array.some(function (object, j) {
if (j === 0) {
vm.roundOf4[i][j] = ascArray[i];
} else if (j === 1) {
vm.roundOf4[i][j] = descArray[i];
}
});
});
但按功能分類的升序排序是不正確的排序位置值,所以它給隨機排序。我不知道這是因爲position是一個字符串值。
我應該用數字來代替嗎?
'1'和'-'是相同的子陣列,但在你需要的輸出他們分開。這背後的邏輯是什麼? –
沒有邏輯,只是「 - 」還沒有設置。它可以是另一個數字,但是因爲它尚未設置,所以它被留在最後,這同樣適用於任何對象。 – forkfork
不是在談論'-',我正在談論'1'和'-'是如何在排序後相互分離的! (**之前:**他們在同一個子陣列中,**之後:**每個人都去了一個不同的子陣列)! '7'和'3'也一樣! –