定义类型和集合
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,
}));
推荐方式二,数据量大时性能最好。
网硕互联帮助中心




评论前必须登录!
注册