需求描述:
给定一个ids数组:
const ids= ['op3', 'op1', 'op2', 'op1']; // ids可能会有重复数据
给定一个list数据:
const list = [
{ id: 'op8', name: '分类op8'},
{ id: 'op7', name: '分类op7'},
{ id: 'op6', name: '分类op6'},
{ id: 'op5', name: '分类op5'},
{ id: 'op3', name: '分类op3'},
{ id: 'op2', name: '分类op2'},
{ id: 'op1', name: '分类op1'},
{ id: 'op5', name: '分类op5'},
{ id: 'op6', name: '分类op6'},
{ id: 'op2', name: '分类op2'},
{ id: 'op2', name: '分类op2'},
{ id: 'op1', name: '分类op1'},
{ id: 'op1', name: '分类op1'},
{ id: 'op111', name: '分类op111'},
{ id: 'op111', name: '分类op111'},
{ id: 'op111', name: '分类op111'},
{ id: 'op111', name: '分类op111'},
{ id: 'op111', name: '分类op111'},
{ id: 'op111', name: '分类op111'},
]
输出:根据ids过滤List,并按照id在ids中的顺序排好序。
const filterCategory = (list, ids) => {
if (!ids.length) return list;
// 根据ids过滤list并且排序
// 目标:只遍历一次list就能过滤出ids中的分类数据并排好序
const valueIndexMap = {}; // 记录ids中的值对应的索引 { v: [ idx1, idx2 ]}
ids.forEach((v, index) => {
const temp = valueIndexMap[v] || []; // 正常情况下,ids中不会有重复的分类ID,但此需求可能会存在重复的分类ID,因此统一使用数组保存索引
valueIndexMap[v] = [...temp, index]; // 如果能保证业务场景下,ids不会有重复id,大可使用valueIndexMap[v] = index;
});
const map = {};
const filterAndSortList = [];
// 只遍历一次list
list.forEach((item) => {
const indexs = valueIndexMap[item.id];
// 过滤
if (indexs) {
indexs.forEach((i) => {
const mapValue = map[i] || [];
map[i] = [...mapValue, item];
});
}
});
Object.keys(map).forEach((k) => {
filterAndSortList.push(...map[k]);
});
return filterAndSortList;
};