1

I have this array

const arr = ['1','2','3',...'30','31','LAST']

I need to sort by number ASC

Here is the example code and I don't know how to sort it. help me please

const arr2 = ['2','1','10','LAST','20']

I need result ['1','2','10','20','LAST'] instead of ['1','10','2','20','LAST']

Agniveer
  • 371
  • 2
  • 18
kkangil
  • 33
  • 3

5 Answers5

1

You could check for NaN and move that value to bottom.

Array#sort sorts without callback by string and does not respect stringed numerical values.

var array = ['2','ZIRST','1','10','LAST','20', 'Sara'];

array.sort((a, b) => isNaN(a) - isNaN(b) || a - b || a > b || -(a < b));

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    This function does't sort array well with multiple words as string: ['5','ZIRST','1','10','LAST','20', 'Sara']. It returns ["1", "5", "10", "20", "ZIRST", "LAST", "Sara"] instead of ["1", "5", "10", "20","LAST", "Sara", "ZIRST"] – MattYao May 23 '18 at 07:09
  • @MattYao, i added a sorting for strings at the end. – Nina Scholz May 23 '18 at 07:20
  • Nice one! Neat and clean code. – MattYao May 23 '18 at 07:25
1

function sortArray(arr) {
  let sortedArr = arr.sort();
  sortedArr.forEach((v, i) => {
    if (!isNaN(parseInt(v))) {
      sortedArr[i] = parseInt(v);
    } else {
      sortedArr[i] = v;
    }
  });

  return sortedArr.sort((a, b) => a - b).map(String);
}
// tests
console.log(sortArray(['2', '1','10','LAST','20']));
console.log(sortArray(['5','ZIRST','1','10','LAST','20', 'Sara']));
MattYao
  • 2,495
  • 15
  • 21
0

You need to check whether the given element in the array is number or not and then sort it accordingly for numbers and strings. You can create a reusable function sortNumber so that it can be used for multiple arrays and you do not need to duplicate the same logic again and again.

function sortNumber(a,b) {
    return isNaN(a) - isNaN(b) || a - b;
}

var inputArray = ['2','1','10','LAST','20'];
inputArray.sort(sortNumber);
console.log(inputArray);

inputArray = ['21','31','110','LAST','220'];
inputArray.sort(sortNumber);
console.log(inputArray);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You can use custom comparator like this:

var arr = ['2','1','10','LAST','20'];
arr.sort((a,b)=>{
  return parseInt(a) > parseInt(b)  || isNaN(a);
});
Tamiros
  • 1
  • 2
0

You can use localeCompare to sort an array on the numeric property.

const array = ["1", "5", "10", "20", "ZERO", "LAST", "Sara"];
array.sort((a, b) => a.localeCompare(b,undefined,{numeric: true}));
console.log(array);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51