在工作中遇到一個問題,在前端頁面上,想把一個數組中的元素按照自己想要的順序排序,研究了一下,收集了以下兩種方案:
方法一:
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'];});
最新評論