【问题标题】:Typescript: Filtering an array by a subset of said array and returning matching IDs打字稿:通过所述数组的子集过滤数组并返回匹配的ID
【发布时间】:2018-09-29 02:15:59
【问题描述】:

假设你有两个数组:

Animals[];

SelectedAnimals[];

当用户搜索新动物时,我们必须确保选中的动物保持选中状态,并且如果新的动物结果不匹配,我们还必须确保过滤掉之前选择的动物。

我的解决方案确实有效,但我担心给定地图、过滤器、过滤器在单个数组上的时间复杂度/hacky-ness。有没有更好的方法使用 JS/Lodash 数组函数来实现我用所述数组的子集过滤数组的目标(并避免未定义的条目)?

new V.Ajax().Post(window.animals.urls.searchAnimals, searchParams).done((response: V.JsonResult) => {
            if (response.success) {
                let newAnimals = response.data.Results as Animal[];
                let selectedAnimals = newAnimals == [] ? [] : this.state.selectedAnimals.map(x => filter(newAnimals, (animal) => animal.AnimalID == x.AnimalID)).filter(item => typeof item === 'number');

【问题讨论】:

  • 我们所说的数组有多长?
  • @Markus 假设最大 1000

标签: javascript arrays typescript lodash


【解决方案1】:

我认为_.includes_.isNumber 可能正是您所需要的!如果 newAnimals 为空或任何 AnimalIds 无效,则下面的代码应该可以工作。

const newAnimalIds = _.map(newAnimals,
      a => a && _.isNumber(a) ? a.AnimalId : null);

const selectedAnimals = _.filter(this.state.selectedAnimals, 
      x => _.includes(newAnimalIds, x.AnimalId));

耶 lodash :)

【讨论】:

  • 太棒了!乐于助人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2021-05-24
  • 2021-11-21
  • 2021-12-15
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多