0

I have a case where i want to filter one javascript object array based on another object array.

    var arrCompany= [];
    var arrUsers = []
    var company =
    {
      companyId:6
    }
    arrCompany.push(company);
    var company =
    {
      companyId:7
    }
    arrCompany.push(company);

    var user =
    { 
    userId:1
    companyId :6
    }

    arrUsers.push(user);

    var user =
    { 
    userId:1
    companyId :7
    }

    arrUsers.push(user);

I want to filter user array(arrUsers) in a such a way that filtered array should contain all the users which are there in arrCompany array (ie:based on company id.Based on above example filtered user array should contain items with Company Id 6&7).I need a solution which works on IE 11.I tried something as below and not working.Can anyone please help on this

var filtered = arrUsers.filter(
function(e) {
  return this.indexOf(e.companyId) < 0;
},
arrComapny.companyId
);
vmb
  • 2,878
  • 15
  • 60
  • 90

2 Answers2

1

Filter users based on whether their companyId appears in the arrCompany array.

Array.some

const filtered = arrUsers.filter((user) => 
  arrCompany.some((company) => company.companyId === user.companyId)
);
James
  • 20,957
  • 5
  • 26
  • 41
1

You can use Array.find within the filtering

const arrCompany= [
  {companyId: 6}, 
  {companyId: 7},
  {companyId: 8},
];
const arrUsers = [
  {userId:1, companyId: 6}, 
  {userId:1, companyId: 7}, 
  {userId:1, companyId: 10},
];
const filtered = arrUsers.filter( usr => 
    // find companyId from current user in arrCompany                            
    arrCompany.find(company => 
      company.companyId === usr.companyId) );

console.log(filtered);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • to support IE11,can i rewrite as below ?var filtered = arrUsers.filter(function (usr) { return (// find companyId from current user in arrCompany arrCompany.find(function (company) { return company.companyId === usr.companyId; }) ); }); – vmb Nov 20 '20 at 12:58
  • @KooiInc..Is it work if i add an additional condition as return company.companyId === usr.companyId && company.IsActive = true – vmb Nov 20 '20 at 13:18
  • `company.IsActive` was not mentioned in your question. `company.IsActive = true` can be written as `company.IsActive`. IE11 should not be supported anymore imho. If you really need it, check [caniuse.com](https://caniuse.com/) or compatibility/polyfills [in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). There are polyfills for `Array[filter, find (and some for that matter)]` – KooiInc Nov 20 '20 at 14:50