云计算百科
云计算领域专业知识百科平台

JS集合去重和排序

定义类型和集合

export interface DeptRoomLocItem {

    DeptId: number;

    DeptName: string;

    RoomId: number;

    RoomName: string;

    RoomNO: string;

    RoomLocId: number;

    RoomLocName: string;

    RoomLocNO: string;

}

const allDeptRoomLocs:DeptRoomLocItem[]=[…..]

 方式一:用 filter + findIndex

const newRoomOptions = allDeptRoomLocs
    .filter(x => x.DeptId === deptId)
    .filter((item, index, arr) => arr.findIndex(x => x.RoomNO === item.RoomNO) === index)
    .sort((s1, s2) => s1.RoomNO.localeCompare(s2.RoomNO))
    .map(x => ({
        label: `${x.RoomName}(NO.:${x.RoomNO})`,
        value: x.RoomId,
    }));

方式二:用 Map(性能更好) 

const newRoomOptions = […new Map(
    allDeptRoomLocs
        .filter(x => x.DeptId === deptId)
        .map(x => [x.RoomNO, x])  // 以 RoomNO 为 key
).values()]
    .sort((s1, s2) => s1.RoomNO.localeCompare(s2.RoomNO))
    .map(x => ({
        label: `${x.RoomName}(NO.:${x.RoomNO})`,
        value: x.RoomId,
    }));

方式三:用 reduce 

const newRoomOptions = allDeptRoomLocs
    .filter(x => x.DeptId === deptId)
    .reduce((acc, cur) => {
        if (!acc.some(x => x.RoomNO === cur.RoomNO)) {
            acc.push(cur);
        }
        return acc;
    }, [] as typeof allDeptRoomLocs)
    .sort((s1, s2) => s1.RoomNO.localeCompare(s2.RoomNO))
    .map(x => ({
        label: `${x.RoomName}(NO.:${x.RoomNO})`,
        value: x.RoomId,
    }));

推荐方式二,数据量大时性能最好。

赞(0)
未经允许不得转载:网硕互联帮助中心 » JS集合去重和排序
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!