简体   繁体   中英

How to sort an array of strings by numerical order?

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

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

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

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

Make a custom sort() function and use slice to get the number of the string and then apply Number() 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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM