Lets say you have two arrays:
Animals[];
SelectedAnimals[];
When the user searches for new animals we have to make sure that selected animals remained checked and we also have to make sure the previously selected animals are filtered out if the new animal results do not have a match.
My solution does work but I'm worried about the time complexity / hacky-ness given a map, filter, filter on a single array. Is there a better approach using JS/Lodash array functions to accomplish my goal of filtering a array with a subset of said array (and avoiding undefined entries)?
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');
答案 0 :(得分:0)
我认为_.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));
Yay lodash:)