【问题标题】:Sort array elements alphabetically after sorting numerically按数字排序后按字母顺序对数组元素进行排序
【发布时间】:2018-05-13 02:06:11
【问题描述】:

假设我有一个数组:

arr = ["Tom, 2, 6","Bill, 3, 8","Lisa, 4, 7","Charles, 2, 8"]

我知道我可以使用arr.split(',',2).pop();,例如,提取每个字符串中的第二个元素,并使用自定义比较函数对它们进行排序。但是,在按数字排序后如何按字母顺序排序?

在这种情况下,例如,包含 Tom 和 Charles 的字符串在第一个逗号后面都有一个 2。按数字排序会使汤姆排在查尔斯之前,但是,我希望它们也按字母顺序出现。那我该怎么做呢?

【问题讨论】:

    标签: jquery arrays sorting


    【解决方案1】:

    您可以在sort()中传递自定义回调函数

    var arr = ["Tom, 2, 6", "Bill, 3, 8", "Lisa, 4, 7", "Charles, 2, 8"];
    
    arr.sort((a, b) => {
      a = a.split(',').map(o => o.trim());     //Split a and trim
      b = b.split(',').map(o => o.trim());     //Split b and trim
    
      if (a[1] !== b[1]) return a[1] - b[1];   //Check if the second value is not the same, if not the same sort using the second value
      return a[0].localeCompare(b[0]);         //Since second value is the same, use the first value to sort
    })
    
    console.log(arr);

    使用姓氏(第二个单词)进行匹配

    var arr = ["Tom Peters, 2, 6", "Bill Burgess, 2, 8", "Lisa Cooper, 4, 7", "Charles White, 2, 8"];
    
    arr.sort((a, b) => {
      a = a.split(',').map(o => o.trim()); //Split a and trim
      b = b.split(',').map(o => o.trim()); //Split b and trim
    
      if (a[1] !== b[1]) return a[1] - b[1]; //Check if the second value is not the same, if not the same sort using the second value
      return a[0].split(' ')[1].localeCompare(b[0].split(' ')[1]); //Since second value is the same, use the first value to sort
    })
    
    console.log(arr);

    文档:sort()

    【讨论】:

    • 感谢您的解决方案。效果很好!我可能应该在我的问题中这么说,但我数组中的名字包括姓氏。我尝试使用return (a[0].split(" ",2).pop()).localeCompare(b[0].split(" ",2).pop()); 按姓氏排序,但它与您的答案具有相同的效果。有什么建议吗?
    • @codeEnthusiast 你能举一个姓氏数组的例子吗?所以按姓氏排序?
    • var arr = ["Tom Peters, 2, 6", "Bill Burgess, 3, 8", "Lisa Cooper, 4, 7", "Charles White, 2, 8"] - 按第二个元素编号排序后的预期结果是,汤姆·彼得斯凭借姓氏领先于查尔斯·怀特。
    • @codeEnthusiast 我们是否假设second 是姓氏。正确的?用户可能有一个名字“John Paul Peters”。还是只使用last 这个词?
    • 是的。第二个单词被假定为姓氏。
    【解决方案2】:

    你为什么不试试排序呢?

    arr.sort();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多