js如何将一个数组按照自己固定的顺序排序?
在工作中遇到一个问题,在前端页面上,想把一个数组中的元素按照自己想要的顺序排序,研究了一下,收集了以下两种方案:
方法一:
var obj=[ {name:"张三",age:12},
{name:"李四",age:13},
{name:"王五",age:18},
{name:"张柳",age:11},
{name:"李强",age:33},
];
想要按照年龄的大小来排序,可以用sort方法:
function sortab(data){
return function(obj1,obj2){
var value1=obj1[data];
var value2=obj2[data];
if(value2<value1){
return 1
}else if(value2>value1){
return -1
}else{
return 0
}
}
}
obj.sort(sortab("age"))
console.log(obj) // [{name: "张柳", age: 11},{name: "张三", age: 12},{name: "李四", age: 13},{name: "王五", age: 18},{name: "李强", age: 33}]
方案二:
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是规则bai objs是需要排序的数du组 var order = ["wipe", "fly", "iris", "flip", "cube", "blur", "zoom", "fade", "glow", "rotate"]; return order.indexOf(a.type) - order.indexOf(b.type); }); // 根据规则排序后zhi新的数组 var result = objs.map(function(a){ return a['name']; });