2 回答
![?](http://img1.sycdn.imooc.com/54585094000184e602200220-100-100.jpg)
TA贡献1854条经验 获得超8个赞
如果你指定你想要的顺序为数组,你可以排序基于每个类别的指标内数组。
var arr = [ {name: 'kim', salary: 4000,CategoryId:3, TypeId:1}, {name: 'shelly', salary: 5000,CategoryId:14, TypeId:1}, {name: 'don', salary: 100,CategoryId:9, TypeId:1}, {name: 'mark', salary: 4500,CategoryId:5, TypeId:2}, {name: 'mark', salary: 4500,CategoryId:5, TypeId:1}, {name: 'joh', salary: 3450,CategoryId:9, TypeId:1}, {name: 'joe', salary: 5100,CategoryId:1, TypeId:1}, {name: 'moore', salary: 5100,CategoryId:14, TypeId:2}, {name: 'wane', salary: 1500,CategoryId:14, TypeId:2}, {name: 'dick', salary: 400,CategoryId:3, TypeId:1} ];
const categoryOrder = [5,9,14,1,9,3];
const result = [...arr].sort((a,b) => {
return a.TypeId === b.TypeId
? categoryOrder.indexOf(a.CategoryId) - categoryOrder.indexOf(b.CategoryId)
: a.TypeId - b.TypeId;
});
console.log(result);
![?](http://img1.sycdn.imooc.com/54584f6d0001759002200220-100-100.jpg)
TA贡献1815条经验 获得超13个赞
为此,您必须制作自己的自定义排序功能,因为使用 underscore.js 无法实现
var tempArray = [
{name: 'kim', salary: 4000, CategoryId: 3, TypeId: 1},
{name: 'shelly', salary: 5000, CategoryId: 4, TypeId: 1},
{name: 'don', salary: 100, CategoryId: 9, TypeId: 1},
{name: 'mark', salary: 4500, CategoryId: 5, TypeId: 2},
{name: 'mark', salary: 4500, CategoryId: 5, TypeId: 1},
{name: 'joh', salary: 3450, CategoryId: 9, TypeId: 1},
{name: 'joe', salary: 5100, CategoryId: 1, TypeId: 1},
{name: 'moore', salary: 5100, CategoryId: 14, TypeId: 2},
{name: 'wane', salary: 1500, CategoryId: 14, TypeId: 2},
{name: 'dick', salary: 400, CategoryId: 3, TypeId: 1}
]
function sort(order, array) {
result = []
order.forEach(o => {
let output = array.filter(element => element.CategoryId === o)
// To further sort it by type id we can now use sort
output = _.sortBy(output, 'TypeId')
result = result.concat(output)
})
// For output to be this way
// TypeID: (1) - order by : 5,9,14,1,9,3, TypeID: 2
// Order by : 5,9,14,11,9,3.
// we can use groupBy
return _.groupBy(result, 'TypeId')
}
sort([5, 9, 14, 1, 9, 3], tempArray)
这回答了你的问题了吗 ?
添加回答
举报