Home > Enterprise >  Filtering two arrays based on another array values and also push the unavailable values into another
Filtering two arrays based on another array values and also push the unavailable values into another

Time:01-24

I have 2 arrays one is "searchEachIndex" and another one is "data".

Based on "searchEachIndex" array i want to filter the "data" array. i.e,

Here in searchEachIndex array i have 123 value that matches with data array's employeId.

should push the object into res array here { id: 2, employeId: 123 }, { id: 3, employeId: 123 }, If both values matches. otherwise push the mismatching searchEachIndex values here 1234, 12 into another array i.e, noData array.

    let searchEachIndex = [123, 1234, 12]

    let data = [
    {
      id: 1,
      employeId: 121
    },
    {
      id: 2,
      employeId: 123
    },
    {
      id: 3,
      employeId: 123
     }
    ];

    let res=[];

    let noData = [];

    searchEachIndex.forEach(val => {
       data.map(item => {
          if(item.employeId === val) {
           res.push(item)
          }
       })
    })


    console.log('Both emp id and searchEachIndex value matched array', res);

    consolelog('Ids not found array', noData);

Actually i need response like the following : res : [{ id: 2, employeId: 123 }, { id: 3, employeId: 123 }] and noData : [1234, 12]

CodePudding user response:

You can substitute the .map with .forEach since you do not require a transformed array returned and are only looking for a for loop.

Also you can keep a boolean flag which lets you know if the current val had a corresponding entry in the data array. That way you can push (/not push) into your noData array.

Building up on your code :

let searchEachIndex = [123, 1234, 12]

let data = [
{
  id: 1,
  employeId: 121
},
{
  id: 2,
  employeId: 123
},
{
  id: 3,
  employeId: 123
 }
];

let res=[];

let noData = [];

searchEachIndex.forEach(val => {
   let found = false;
   data.forEach(item => {
      if(item.employeId === val) {
       found = true;
       res.push(item)
      }
   })
   if(!found) noData.push(val);
})

console.log('Both emp id and searchEachIndex value matched array', res);

console.log('Ids not found array', noData);

CodePudding user response:

You could take an object to keep track of used values and filter the arrays.

const
    search = [123, 1234, 12],
    used = Object.fromEntries(search.map(k => [k, false])),
    data = [{ id: 1, employeId: 121 }, { id: 2, employeId: 123 }, { id: 3, employeId: 123 }],
    result = data.filter(({ employeId }) => {
        if (employeId in used) return used[employeId] = true;
    }),
    noData = search.filter(k => !used[k]);

console.log(noData);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  •  Tags:  
  • Related