简体   繁体   中英

How to sort two dimentional array with string based on length?

I have two dimentional array and i wan to sort in on order and based on string length. how can i do it? this is my code:

 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); 

i want it to become in this order

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

how can I do it?

Is this what you are trying to achieve?

 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) 

You might use a single sort with a callback which respects the length of the first item of the inner arrays with using the difference of the length. If the length is equal take String#localeCompare for sorting by alphabet.

 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; } 

Check if lengths differ. If they do, sort by them. If equal, sort alphabetically:

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);

try this

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM