按升序排列数组元素(数字作为数组元素中的子字符串)



我有一个数组,我想按升序定位每个数组元素,但数字是作为数组元素的子字符串找到的。我草拟了下面的代码,让你了解我正在努力实现的目标(它很有效,但很难看(。当数字作为数组元素中的子字符串时,按升序定位数组中每个元素的最佳方法是什么。提前谢谢。

看看我的代码,更好地理解我的问题!

//this works but is uglyyyyy
const myArray = ['test4.js', 'test3.js', 'test1.js', 'test2.js']
let tempArr = []
for (var i = 0; i < myArray.length; i++) {
tempArr.push(myArray[i].replace('test', '').replace('.js', ''))
}
const sortedTempArr = tempArr.sort()
let sortedArray = []
for (var i = 0; i < sortedTempArr.length; i++) {
for (var j = 0; j < myArray.length; j++) {
if (myArray[j].includes(sortedTempArr[i])) {
sortedArray.push(myArray[j])
}
}
}
console.log(sortedArray)

是的,那很难看;(

排序采用功能

下降时,切换ab

我假设字符串中只有一个数字。如果您有test2version1.js(例如(,正则表达式将产生错误的结果

//this works and is pretty
const myArray = ['test4.js', 'test3.js', 'test11.js', 'test1.js', 'test.js', 'test2.js']; 
const re = /D+/g; // anything not a number
const sortedArray = myArray
.slice(0) // shallow copy
.sort((a, b) => a.replace(re, "") - b.replace(re, ""));
console.log(sortedArray);

.sort()每个字符串的.match(/d+/)[0]编号(强制为数字(。括号表示法([0](确保只使用第一个匹配项,而忽略其他所有匹配项。

const array = ['test4.js','test11.js', 'test3.js', 'test1.js', 'test2.js'];
let result = array.sort((a, b) => +a.match(/d+/)[0] - b.match(/d+/)[0]);
console.log(result);

最新更新