[英]How to sort an array by numbers in strings?
I have an array:我有一个数组:
[
'B3', 'B4', 'B5',
'B6', 'C3', 'C4',
'C5', 'C6', 'D3',
'D4', 'D5', 'D6'
]
I need to sort it by the number in each string (in ascending order).我需要按每个字符串中的数字(按升序)对其进行排序。 The number can be one/double-digit/triple-digit.
该数字可以是一位/两位数/三位数。
Here's what the final array should look like:这是最终数组的样子:
[
'B3', 'C3', 'D3',
'B4', 'C4', 'D4',
'B5', 'C5', 'D5',
'B6', 'C6', 'D6'
]
How can I do it?我该怎么做?
Assuming that there will always be only one letter at the beginning - then here is the solution:假设开头总是只有一个字母 - 那么解决方案如下:
const input = [ 'B3', 'B4', 'B5', 'B6', 'C3', 'C4', 'C5', 'C645', 'D3', 'D4', 'D532', 'D6' ]; console.log(sort(input)); function sort(array) { return array.sort((a, b) => { const aVal = parseInt(a.slice(1), 10); const bVal = parseInt(b.slice(1), 10); if (aVal < bVal) { return -1; } if (aVal > bVal) { return 1; } return 0; }); }
You can have a look to the sort method: https://www.w3schools.com/jsref/jsref_sort.asp你可以看看排序方法: https://www.w3schools.com/jsref/jsref_sort.asp
And how you can pass a function in for values comparison as a criteria to sort the elements:)以及如何通过 function 进行值比较作为对元素进行排序的标准:)
const myArray = [ 'B3', 'B4', 'B5', 'B6', 'C3', 'C4', 'C5', 'C6', 'D3', 'D4', 'D5', 'D6' ] const sortedArray = myArray.sort((a, b) => a[1] - b[1]) console.log(sortedArray)
You can use sort
method of array with custom comparator function as:您可以将数组的
sort
方法与自定义比较器 function 一起使用:
const arr = [ 'B3', 'B4', 'B5', 'B6', 'C3', 'C4', 'C5', 'C6', 'D3', 'D4', 'D5', 'D6', ]; const result = arr.sort((a, b) => +a.match(/\d+/) - +b.match(/\d+/)); console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */.as-console-wrapper { max-height: 100%;important: top; 0 }
Here is what I came up with:这是我想出的:
const sortByNum = arr => {
let newArr = arr.map(item => {
return {
letter: item[0],
number: item.substr(1, item.length),
};
});
newArr.sort((numA, numB) => numA.number - numB.number);
return newArr.map(item => {
return (item.letter + item.number);
});
};
its basically dividing each string into key/value pairs, sorting them by number, then joining them back into strings.它基本上将每个字符串分成键/值对,按数字排序,然后将它们重新连接成字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.