Reputation: 556
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?
Upvotes: 4
Views: 67
Reputation: 386654
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; }
Upvotes: 1
Reputation: 4207
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)
Upvotes: 0
Reputation: 984
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)
Upvotes: 1
Reputation: 9937
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);
Upvotes: 0