3

For example, i have a string array ['item 2','item 1','item 10','item 4']. I want it to be like this ['item 1','item 2','item 4','item 10'] but by default, the sort() function sorts values by alphabetical order, which means it will look like this ['item 1','item 10','item 2','item 4']

1
  • With that particular input (and its variants, a constant string following by a number), array.sort((a, b) => a.localeCompare(b, 'EN', {numeric: true})); will do the trick. Commented Jun 4, 2021 at 10:18

6 Answers 6

5

Just get the number and sort it

let array = ["item 1", "item 10", "item 2", "item 4"];

const result = array.sort((a, b) => a.match(/\d+/) - b.match(/\d+/));
console.log(result);

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

Comments

3

You can add custom compare function in array.sort

const myArr = ['item 2','item 1','item 10','item 4'];
const sortArr = myArr.sort((a, b) => {
  const num1 = Number(a.split(' ')[1]);
  const num2 = Number(b.split(' ')[1]);
  return num1 - num2;
});
console.log(sortArr);

or simply

const myArr = ['item 2','item 1','item 10','item 4'];
const sortArr = myArr.sort((a, b) => Number(a.split(' ')[1]) - Number(b.split(' ')[1]))
console.log(sortArr);

Comments

2

You can pass a function to sort() method and sort it on custom way

let result = arr.sort((a,b) => a.split(' ')[1]-b.split(' ')[1])

console.log(result);

Comments

2
let array = ['item 1','item 10','item 2','item 4'];
var customSort = function (a, b) {
    return Number(a.replace("item ","")) - Number(b.replace("item ",""));  
}
console.log(array.sort(customSort));
//one line
console.log(array.sort((a,b) => Number(a.replace("item ","")) - Number(b.replace("item ",""))));

Comments

2

Make a custom sort() function and use slice to get the number of the string and then applyNumber() to transform it to a number for comparison.

Note: sort() will update the original array.

const array = ["item 1", "item 10", "item 2", "item 4"];
array.sort((a, b) => Number(a.slice(5)) - Number(b.slice(5)));

console.log(array);

Comments

2

You can pick any answer. This is a more generic solution, for sorting strings ending with numeric values (or not).

const toNumberOrZero = str => {
  const maybeNumber = str.match(/(\d+)$/);
  return maybeNumber && +maybeNumber[0] || 0;
};
const sortNumericForStringsEndingWithNumbers = (a, b) =>
  toNumberOrZero(a) - toNumberOrZero(b);

console.log(
  ['item 2', 'item 1', 'item 10', 'item 4', 'item222', 
    'anything1023', 'notanumber', 'the meaning of life is 42']
  .sort(sortNumericForStringsEndingWithNumbers)
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.