如何根据字符串中的数字对数组进行排序? [英] How to sort array based on the numbers in string?
问题描述
给出此数组= [ "3ab1", "2a0", "1abc2" ]
如何将其排序为[ "1abc2", "3ab1", "2a0" ]
(最后一个数字的降序)
How do I sort it to [ "1abc2", "3ab1", "2a0" ]
(descending order of the last number)
并返回[ 1,3,2 ]
. (每学期的第一个数字)
and return [ 1,3,2 ]
. (the first numbers of each term)
当最后一个数字和下一个最后一个数字不连续时,返回的值应为0.
When the last number and the next last number is not consecutive, the value returned should be 0.
[ "2x2", "3x0", "2x1" ] ==> [ 2, 2, 3 ]
[ "22x0", "3x9", "2x1" ] ==> [ 3, 0, 0, 0, 0, 0, 0, 0, 2, 22 ]
[ "2x4", "3x0" ] ==> [ 2, 0, 0, 3 ]
[ "axn", "bx(n-2)" ] ==> [ "axn", "0x(n-1)", bx(n-2) ] ==> [ a, 0, b ]
我正在考虑将数组转换为字符串,替换前面的数字和字母,然后对数组进行排序.但是我不知道如何将更换的零件放回原来的编号.这是我对排序后的最终数组返回的尝试.
I was thinking of converting to the array to string, replacing the number and letters in front and then sorting the array. But I do not know how put the part that was replaced back to its original number. This is my attempt on returning the final array once it is sorted.
var ary = [ "1abc2", "3ab1", "2a0" ];
console.log(((ary.toString()).match(/\d+(?!,)/g)).slice(0, -1));
我在根据数字对数组进行排序时看到了这些问题,但它们似乎对我不起作用.
I saw these questions on sorting arrays based on numbers but they do not seem to work for me.
推荐答案
使用sort
和reduce
获取结果时,可以使用正则表达式获取数字:
You can use regular expression to get the numbers when using sort
and reduce
to get the result:
var array = [ "22x0", "3x9", "2x1" ];
var reS = /^\d+/, // regexp for getting all digits at the start of the string
reE = /\d+$/; // regexp for getting all digits at the end of the string
var result = array.sort(function(a, b) { // First: sort the array
a = reE.exec(a); // get the last number from the string a
b = reE.exec(b); // get the last number from the string b
return b - a; // sort in a descending order
}).reduce(function(res, str, i) { // Then: accumulate the result array
var gap = reE.exec(array[i - 1]) - reE.exec(str); // calculate the gap between this string str and the last string array[i - 1] (gap = N_of_last_string - N_of_this_string)
if(gap > 0) // if there is a gap
while(--gap) res.push(0); // then fill it with 0s
res.push(+reS.exec(str)); // push this string number
return res;
}, []);
console.log("Sorted array:", array); // array is now sorted
console.log("Result:", result); // result contain the numbers
在最新的ECMAScript版本中,您可以使用以下箭头功能很快完成此操作:
In recent ECMAScript versions you can do it shortly using arrow functions like this:
let array = [ "22x0", "3x9", "2x1" ];
let reS = /^\d+/,
reE = /\d+$/;
let result = array.sort((a, b) => reE.exec(b) - reE.exec(a))
.reduce((res, str, i) => {
let gap = reE.exec(array[i - 1]) - reE.exec(str);
if(gap > 0)
while(--gap) res.push(0);
res.push(+reS.exec(str));
return res;
}, []);
console.log("Sorted array:", array);
console.log("Result:", result);
这篇关于如何根据字符串中的数字对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!