How to sort two massive arrays with a string by length?

I have two array sizes and I want to sort in order and based on the length of the string. How should 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);
Run codeHide result

I want him to become in that order

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

How can i do this?

+4
source share
4 answers

You can use one view with a callback that takes into account the length of the first element of the internal arrays using the length difference. If the length is equal, String#localeCompareto sort alphabetically.

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; }
Run codeHide result
+1
source

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)
Run codeHide result
+1
source

, . , . , :

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)
Hide result
0

Source: https://habr.com/ru/post/1685273/


All Articles