Underscore.js sort an array of objects alphanumerically

后端 未结 3 1162
耶瑟儿~
耶瑟儿~ 2021-01-16 18:49

I have an array of objects and I\'m trying to sort them alphanumerically, take the following example:

var objs = {
    \'obj1\': {\'name\': \'Object21\'},
           


        
3条回答
  •  粉色の甜心
    2021-01-16 19:52

    You need the Alphanum sorting algorithm and an elegant implementation in JavaScript:

    function alphanum(a, b) {
      function chunkify(t) {
        var tz = [], x = 0, y = -1, n = 0, i, j;
    
        while (i = (j = t.charAt(x++)).charCodeAt(0)) {
          var m = (i == 46 || (i >=48 && i <= 57));
          if (m !== n) {
            tz[++y] = "";
            n = m;
          }
          tz[y] += j;
        }
        return tz;
      }
    
      var aa = chunkify(a);
      var bb = chunkify(b);
    
      for (x = 0; aa[x] && bb[x]; x++) {
        if (aa[x] !== bb[x]) {
          var c = Number(aa[x]), d = Number(bb[x]);
          if (c == aa[x] && d == bb[x]) {
            return c - d;
          } else return (aa[x] > bb[x]) ? 1 : -1;
        }
      }
      return aa.length - bb.length;
    }
    

提交回复
热议问题