我有一个像下面这样的单词数组:
arr = ["id1 abc test", "id#2 XX car house", "id-3 abc home"]我想对它进行排序,但忽略了第一个单词。例如,输出将是:
arr = ["id-3 abc home", "id1 abc test", "id#2 XX car house"]谢谢
发布于 2020-08-08 03:23:13
function getStringWithoutFirstWord(str) {
return str.split(/\s+/).slice(1).join(' ');
}
function compareLoacallyWhilstIgnoringFirstWord(a, b) {
a = getStringWithoutFirstWord(a); // yes, this is a ...
b = getStringWithoutFirstWord(b); // ... highly repetitive task.
return a.localeCompare(b);
}
function compareStronglyAscendingWhilstIgnoringFirstWord(a, b) {
a = getStringWithoutFirstWord(a); // yes, this is a ...
b = getStringWithoutFirstWord(b); // ... highly repetitive task.
return ((a < b && -1) || (a > b && 1) || 0);
}
const arr = ["id1 abc test", "id#2 XX car house", "id-3 abc home"];
console.log(
arr.sort(compareLoacallyWhilstIgnoringFirstWord)
);
console.log(
arr.sort(compareStronglyAscendingWhilstIgnoringFirstWord)
);.as-console-wrapper { min-height: 100%!important; top: 0; }
..。Hassan Imam已经提到的方法的一个工作实现……
function getStringWithoutFirstWord(str) {
return str.split(/\s+/).slice(1).join(' ');
}
function restoreStringFromDecoratedIgnoredFirstWordData(data) {
return data.original;
}
function createDecoratedIgnoredFirstWordData(str) {
return {
original: str,
sortable: getStringWithoutFirstWord(str)
}
}
function compareSortablesLoacally(a, b) {
return a.sortable.localeCompare(b.sortable);
}
function compareSortablesStronglyAscending(a, b) {
a = a.sortable;
b = b.sortable;
return ((a < b && -1) || (a > b && 1) || 0);
}
const arr = ["id1 abc test", "id#2 XX car house", "id-3 abc home"];
console.log(arr
.map(createDecoratedIgnoredFirstWordData)
.sort(compareSortablesLoacally)
.map(restoreStringFromDecoratedIgnoredFirstWordData)
);
console.log(arr
.map(createDecoratedIgnoredFirstWordData)
.sort(compareSortablesStronglyAscending)
.map(restoreStringFromDecoratedIgnoredFirstWordData)
);.as-console-wrapper { min-height: 100%!important; top: 0; }
发布于 2020-08-08 19:07:20
这可以用常规的Array.prototype.sort和一个忽略第一个单词的小正则表达式来完成:
const arr = ["id1 abc test", "id#2 XX car house", "id-3 abc home"]
const result = arr.sort((a,b) => {
const [aStr, bStr] = [a,b].map(l => l.replace(/^\S+/g,''));
return aStr.localeCompare(bStr)
})
console.log(result);
https://stackoverflow.com/questions/63304788
复制相似问题