简体   繁体   中英

Filter javascript object array based on another array -Javascript

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM