js Set 去重优化

场景:往tempListExtra塞入数据,返回过滤后的数组。

const arr = [...tempListExtra, ...extraOpt];
const set = new Set();
const duplication = arr.filter((item: any) => {
  if (set.has(item.code)) {
    return false;
  }
  set.add(item.code);
  return true;
});

场景:使用antd的select,当数据是通过接口请求,并且携带分页或者搜索条件时(也就是初次不会展示全数据)

<Select
  showSearch
  mode="multiple"
  placeholder="请选择"
  optionFilterProp="label"
  onSearch={(value) => {
    api(value);
  }}
  options={taskObjOpts}
  onChange={(value, option: any) => {
    // 这里的value会返回所有的ids,包括未在当前查询的数据
    // option则是,如果当前的数据则返回正常,非当前数据返回是{},就会存在
    // [{},{},{正常数据}]
  }}
/>;

所以考虑把ids储存起来,option过滤{}数据保存起来,再通过Set方式去重获取到当前选中的数据

const set = new Set<number>(ids);
const checkedList = options.filter((extra) =>
  set.has(extra.id)
);
posted @ 2023-03-11 22:10  被咯苏州  阅读(33)  评论(0编辑  收藏  举报