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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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; }) ); });
@KooiInc..Is it work if i add an additional condition as return company.companyId === usr.companyId && company.IsActive = true
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 or compatibility/polyfills in MDN. There are polyfills for Array[filter, find (and some for that matter)]
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)
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.