美文网首页
sort string

sort string

作者: 老虎爱吃母鸡 | 来源:发表于2017-07-03 15:17 被阅读0次

    一般Array.prototype.sort用来排序数字,如果用来排序字符串,可以先转换成数字,然后方便排序

    /**
     * 可自定义排序顺序,例如: ['limit', 'reverse', 'new'],就表示limit永远在最前面,然后是reverse,然后是new,最后是不在数组中的
     */
    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)
        // 结果如下
        assert.deepEqual(test, [
            {
                promotionType: 'limit',
            },
            {
                promotionType: 'reverse',
            },
            {
                promotionType: 'new',
            },
        ]);
    

    相关文章

      网友评论

          本文标题:sort string

          本文链接:https://www.haomeiwen.com/subject/yfzacxtx.html