2017-09-08 28 views
4

我有兩個二維數組,我想按順序排序並基於字符串長度。我該怎麼做?這是我的代碼:如何使用基於長度的字符串對兩個二維數組進行排序?

arr = [['ab',0],['ax',0],['ac',0],['bsd',0],['ad',0],['asd',0],['bd',0],['ay',0]]; 
 
function sortByLen(a,b){ 
 
    return (a[0] < b[0]) ? -1 : 1; 
 
} 
 
arr.sort(sortByLen); 
 
console.log(arr);

我希望它成爲這個順序

["ab", 0] 
["ac", 0] 
["ad", 0] 
["ax", 0] 
["ay", 0] 
["bd", 0] 
["asd", 0] 
["bsd", 0] 

我該怎麼辦呢?

回答

1

你可能會使用一個排序與尊重內陣列與第一項的長度回調使用長度的差異。如果長度相同,則按字母順序排列。

var array = [['ab', 0], ['ax', 0], ['ac', 0], ['bsd', 0], ['ad', 0], ['asd', 0], ['bd', 0], ['ay', 0]]; 
 

 
array.sort(function (a, b) { 
 
    return a[0].length - b[0].length || a[0].localeCompare(b[0]); 
 
}); 
 

 
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

這是你想要實現的嗎?

var arr = [['ab',0],['ax',0],['ac',0],['bsd',0],['ad',0],['asd',0],['bd',0],['ay',0]]; 
 

 
var sorted = arr.sort(function(a,b) { 
 
    return a > b 
 
    }).sort(function(a,b) { 
 
    return a[0].length - b[0].length 
 
    }) 
 

 
console.log('sorted',sorted)

+0

雙排序是一個太多,因爲第二個不尊重第一分揀。 –

+0

第二種排序適用於按字母順序排序的數組。儘管我的答案更具可讀性,但您的答案會提供更好的性能! –

+0

不是真的,因爲['Array#sort'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)不穩定,另一種破壞最後一個排序。 –

0

檢查長度不同。如果他們這樣做,按照他們排序。如果相等,按字母順序排序:

var arr = [['ab',0],['ax',0],['ac',0],['bsd',0],['ad',0],['asd',0],['bd',0],['ay',0]]; 
function sortByLen(a,b){ 
    if(a[0].length < b[0].length) return -1; 
    if(a[0].length > b[0].length) return 1; 
    if(a[0] < b[0]) return -1; 
    if(a[0] > b[0]) return 1; 
    return 0; 
} 
arr.sort(sortByLen); 
console.log(arr); 
0

試試這個

arr = [['ac',0],['ab',0],['ax',0],['bsd',0],['ad',0],['asd',0],['bd',0],['ay',0]]; 
 

 
const sortedItems = arr 
 
    .sort((a, b) => a[0] > b[0]) 
 
    .sort((a, b) => a[0].length > b[0].length) 
 

 
console.log(sortedItems)

+0

雙重排序是一個太多,因爲第二個不尊重第一個排序。 –

相關問題