js - 取最大值 - reduce、forEach、sort、的实际应用,Array.prototype

        const formData = {
          ruleList: [
            {sort: 1},
            {sort: 99},
            {sort: 98},
            {sort: 99},
            {sort: 2},
            {sort: 2},
            {sort: 6},
            {sort: 0},
          ]
        }
        // 求sort最大的子项 start
        const rList = formData.ruleList;
        // 方法1
        // const maxSort = rList.length
        //   ? rList.reduce((begin: any, next?: any) =>
        //       (begin?.sort || 0) > (next?.sort || 0) ? begin : next
        //     ).sort || 1
        //   : 1;
        // 方法2
        // let maxSort = 1;
        // rList.forEach((item: any) => {
        //   if (item.sort > maxSort) {
        //     maxSort = item.sort;
        //   }
        // });
        // 方法3
          const maxSort: any = rList.length
            ? rList.sort((first, second) => (first?.sort || 0) - (second?.sort || 0))[
                rList.length - 1
              ].sort
            : 1;
// 求sort最大的子项 end

 

posted @ 2022-04-26 10:08  Noliebe  阅读(94)  评论(0编辑  收藏  举报