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']

0

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

3 Comments

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, i added a sorting for strings at the end.
Nice one! Neat and clean code.
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']));

Comments

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.