【问题标题】:Sort an array of object with a string name parameter containing a number [duplicate]使用包含数字的字符串名称参数对对象数组进行排序[重复]
【发布时间】:2021-11-19 15:34:01
【问题描述】:

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

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?"}]

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

【问题讨论】:

  • 您期望“问题 1#1”->“问题 1#3”->“问题 2#2”->“问题 2#3”还是“问题 1#1”- > “问题 2#2” -> “问题 1#3” -> “问题 2#4”?
  • 你需要使用正则表达式来获取#之后的数字,然后使用该数字对其进行排序。
  • @VLAZ 我期待“问题 1#1”->“问题 2#2”->“问题 1#3”->“问题 2#4”
  • @Terry .split() 怎么了?
  • @vlaz 我没说 OP 不应该使用 split...?

标签: javascript arrays sorting object


【解决方案1】:

最简单的方法:

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));

【讨论】:

    【解决方案2】:

    只需在# 上拆分名称,然后访问该号码。根据这个数字对数组进行排序。

    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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-11
      • 2020-02-18
      • 2016-11-14
      • 1970-01-01
      • 2016-07-02
      • 2020-09-04
      • 1970-01-01
      相关资源
      最近更新 更多