Javascript 数组 根据特定规则排序

var objs = [
    {'name': 'A', 'type': 'fly'},
    {'name': 'B', 'type': 'blur'},
    {'name': 'C', 'type': 'wipe'},
    {'name': 'D', 'type': 'cube'},
    {'name': 'E', 'type': 'iris'},
    {'name': 'F', 'type': 'fade'}
];

objs.sort(function(a,b){
    // order是规则  objs是需要排序的数组
    var order = ["wipe", "fly", "iris", "flip", "cube",
        "blur", "zoom", "fade", "glow", "rotate"];
    return order.indexOf(a.type) - order.indexOf(b.type);
});

// 根据规则排序后新的数组
var result = objs.map(function(a){
    return a['name'];
});

alert('Current order is: ' + result.join(', '));

猜你喜欢

转载自blog.csdn.net/sinat_15951543/article/details/86494939