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

时间:2018-05-13 02:06:11

标签: jquery arrays sorting

假设我有一个数组:

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

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

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

1 个答案:

答案 0 :(得分: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);

Doc:sort()