代码之家  ›  专栏  ›  技术社区  ›  codeEnthusiast

数字排序后按字母顺序对数组元素排序

  •  -1
  • codeEnthusiast  · 技术社区  · 7 年前

    假设我有一个数组:

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

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

    例如,在本例中,包含Tom和Charles的字符串在第一个逗号后都有一个2。按数字排序会使汤姆排在查尔斯之前,但我希望他们也按字母顺序排列。那么我该怎么做呢?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Eddie    7 年前

    可以在中传递自定义回调函数 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()

        2
  •  0
  •   d3t0x    7 年前

    你为什么不试试排序呢?

    arr.sort();