Search code examples
javascriptarraystypescriptlodash

Typescript: Filtering an array by a subset of said array and returning matching IDs


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');


Solution

  • I think _.includes and _.isNumber might be just what you need! The code below ought to work if newAnimals is empty or if any of the AnimalIds are invalid.

    const newAnimalIds = _.map(newAnimals,
          a => a && _.isNumber(a) ? a.AnimalId : null);
    
    const selectedAnimals = _.filter(this.state.selectedAnimals, 
          x => _.includes(newAnimalIds, x.AnimalId));
    

    Yay lodash :)