2 回答

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊
如果你指定你想要的順序?yàn)閿?shù)組,你可以排序基于每個(gè)類別的指標(biāo)內(nèi)數(shù)組。
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);

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
為此,您必須制作自己的自定義排序功能,因?yàn)槭褂?underscore.js 無法實(shí)現(xiàn)
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)
這回答了你的問題了嗎 ?
添加回答
舉報(bào)