Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter typescript array based on another array

There are several examples of this based on simple arrays, but I have 2 arrays of objects and cannot seem to get this to work.

getAvailableApplications() : Application[]
  {
  var list;
  if (!this.userSettings)
    list = this.applications;
  else
    list =  
      this.applications.filter(x=>
      this.userSettings.modules.filter(y=>
       x.entityId === y.moduleId
     ));

return list;    
}

This is always returning me the complete list of applications, and not removing ones that are not in the userSetting.modules array, despite the fact that I have an element in the userSettings.modules array.

I also tried rewriting without lambdas, but it doesn't seem to recognise the module level userSettings variable

      this.applications.filter(function (x){
    return this.userSettings.filter(function(y){
        return x.entityId === y.moduleId;
    })

userSettings is declared as any, but is assigned a value like

  userSettings = {"settings":{"modules":[{"moduleId":"b37f590de59943278e7f9b2137c0c232",
  "order":0}]}

applications is declared like so:

 applications : Application[]
like image 223
jazza1000 Avatar asked Oct 16 '25 07:10

jazza1000


2 Answers

If I understood correctly, this is what you are trying to achieve, no need to use two filters.

list = this.applications
  .filter(x => this.userSettings.modules.map(y => y.moduleId).includes(x.entityId));

See example:

const first = [{entityId: 1}, {entityId: 2}, {entityId: 3}];
const second = [{moduleId: 1}, {moduleId: 3}];

const list = first.filter(x => second.map(y => y.moduleId).includes(x.entityId));

console.log(list);
like image 102
bugs Avatar answered Oct 17 '25 21:10

bugs


Here what you want to accomplish:

this.applications.filter(x => 
    this.userSettings.some(y => 
        x.entityId === y.moduleId;
    )
)

"The some() method tests whether at least one element in the array passes the test implemented by the provided function."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

like image 21
David Faure Avatar answered Oct 17 '25 19:10

David Faure