Underscore.js sort an array of objects alphanumerically

后端 未结 3 1161
耶瑟儿~
耶瑟儿~ 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:31

    You will need to create your own iterator function and then use it, you can't actually do this with the iterator function, but you can get close to it:

    var objs = {
        'obj1': {'name': 'Object21'},
        'obj2': {'name': 'Object140'},
        'obj3': {'name': 'Object28'},
        'obj4': {'name': 'AnObject251'}
    };
    
    _.sortBy(objs, function(obj) {
        var cc = [], s = obj.name;
        for(var i = 0, c; c = s.charAt(i); i++) 
            c == +c ? cc.push(+c) : cc.push(c.charCodeAt(0));
        return +cc.join('');
    });
    
    > Object21
      Object28
      Object140
      AnObject251
    

    "AnObject251" goes on the last place because of its length.

提交回复
热议问题