一般Array.prototype.sort
用來排序數(shù)字宏悦,如果用來排序字符串,可以先轉(zhuǎn)換成數(shù)字粥谬,然后方便排序
/**
* 可自定義排序順序肛根,例如: ['limit', 'reverse', 'new'],就表示limit永遠(yuǎn)在最前面漏策,然后是reverse派哲,然后是new,最后是不在數(shù)組中的
*/
const sortGenerator = (order, sortProperty) => (a, b) => {
const orderOfA = order.indexOf(a[sortProperty]);
const orderOfB = order.indexOf(b[sortProperty]);
if (orderOfA !== -1 && orderOfB !== -1) return orderOfA - orderOfB;
if (orderOfA !== -1 && orderOfB === -1) return -1;
if (orderOfA === -1 && orderOfB !== -1) return 1;
if (orderOfA === -1 && orderOfB === -1) return 0;
};
這樣掺喻,例如
const test = [
{
promotionType: 'new',
},
{
promotionType: 'reverse',
},
{
promotionType: 'limit',
},
];
const sortFn = sortGenerator(['limit', 'reverse', 'new'], 'promotionType') // 定義順序和排序的屬性
test.sort(sortFn)
// 結(jié)果如下
assert.deepEqual(test, [
{
promotionType: 'limit',
},
{
promotionType: 'reverse',
},
{
promotionType: 'new',
},
]);