对包含数字的字符串名称参数的对象数组进行排序



我必须对对象数组进行排序,每个对象的名称中都有一个数字。示例

const question = [{name:"Question 1 #1", content:"blabla?"}, {name:"Question 1 #3", content:"blabla?"}, {name:"Question 1 #4", content:"blabla?"}, {name:"Question 1 #2", content:"blabla?"}]

如何按#后面的数字排序?

最简单的方法:

function sortFunction( a, b ) {
const aNumber = parseInt(a.name.split('#')[1]);
const bNumber = parseInt(b.name.split('#')[1]);
if ( aNumber < bNumber ){
return -1;
}
if ( aNumber >bNumber ){
return 1;
}
return 0;
}
const question = [{name:"Question 1 #3", content:"blabla?"}, {name:"Question 1 #4", content:"blabla?"}, {name:"Question 1 #1", content:"blabla?"}, {name:"Question 1 #2", content:"blabla?"}]
console.log(question.sort(sortFunction));

#上拆分名称并访问之后的数字。根据这个数字对数组进行排序。

const question = [{name:"Question 1 #1", content:"blabla?"}, {name:"Question 1 #3", content:"blabla?"}, {name:"Question 1 #4", content:"blabla?"}, {name:"Question 1 #2", content:"blabla?"}]
const getNumeric = (name) => Number(name.split('#')[1]?.trim() || 0);
const sortedQuestion = question.sort((a, b) => getNumeric(a.name) > getNumeric(b.name) ? 1 : getNumeric(a.name) === getNumeric(b.name) ? 0 : -1);
console.log(sortedQuestion);

最新更新