角度2自定义字母管道排序

时间:2017-08-01 03:19:18

标签: angular sorting angular-pipe

假设我有一个字符串数组:

async.parallel

我可以使用管道按字母顺序排序:

this.data = [ 'cupcake', 'donut', 'eclair', 'froyo', 'gingerbread', 'icecream', 'lollipop', 'marshmallow', 'nougat', 'oreo' ]

我的问题是我怎么能用自定义的字母顺序对它们进行排序,例如我想首先显示“e”,然后是“g”,然后是“m”等。所以顺序看起来像:eclair,gingerbread,棉花糖和其他可以按字母顺序或其他指定的顺序?

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

花了一些时间想出一个表达它的好方法。

请注意,在此实施中,e始终位于a前面,因此ee会在ea前面排序

var data = [ 'cupcake', 'donut', 'eclair', 'froyo', 'gingerbread', 'icecream', 'lollipop', 'marshmallow', 'nougat', 'oreo' ]

data.sort(function(a, b) {
  var i = 0;
  
  while (true) {
    if (i > a.length && i > b.length) return 0;
    else if (i > a.length) return -1;
    else if (i > b.length) return 1;
    else {
      var compare = compareChar(a.charAt(i), b.charAt(i));
      if (compare != 0) return compare;
      i++;
    }
  }

  function compareChar(a, b) {
    var special = ["e", "g", "m"];
    
    var ia = special.indexOf(a);
    var ib = special.indexOf(b);

    if (ia != -1 && ib != -1) { // both special char
      return (ia == ib) ? 0 : (ia < ib) ? -1 : 1;
    }
    else if (ia != -1 && ib == -1) {
      return -1;
    }
    else if (ia == -1 && ib != -1) {
      return 1;
    }
    else {
      return (a == b) ? 0 : (a < b) ? -1 : 1;
    }
  }
});

document.body.innerHTML = data.toString();

相关问题