Arvind Chourasiya
Arvind Chourasiya

Reputation: 17402

How to match few words from a string to filter array items

I have two arrays. One has multiple fields and Name field, another one has only Name field. I want to filter array items from first array based on 2nd array Name. My first array

{
    "Failed": 0,
    "Resume": false,
    "Name": "GRP.Compiled.Release"
},
{
    "Failed": 0,
    "Resume": false,
    "Name": "GPST.NonPermit.Inacitve"
},
{
    "Failed": 0,
    "Resume": false,
    "Name": "PGVF.NonSubmit.Action"
},
{
   "Failed": 0,
   "Resume": false,
   "Name": "PGVF.NonSubmit.Action"
},

I have one more array Names only with Name field

{
    "Name": "NonSubmit"
},
{
    "Name": "NonPermit"
},

This is my code which is not working

for (let i = 0; i < Names.length; i++)
{
   //let obj1=products.filter(x=>Names[i].search(/x.Name/g))
   var obj2=products.filter(x=>Names[i].includes(x.Name))
}

The first iteration I am looking for below output

{
    "Failed": 0,
    "Resume": false,
    "Name": "GPST.NonPermit.Inacitve"
},
{
    "Failed": 0,
    "Resume": false,
    "Name": "PGVF.NonSubmit.Action"
},
{
    "Failed": 0,
    "Resume": false,
    "Name": "PGVF.NonSubmit.Action"
},

How can I do that?

Upvotes: 0

Views: 539

Answers (2)

Prime
Prime

Reputation: 2849

const array1 = [
  {
    "Failed": 0,
    "Resume": false,
    "Name": "GRP.Compiled.Release"
  },
  {
      "Failed": 0,
      "Resume": false,
      "Name": "GPST.NonPermit.Inacitve"
  },
  {
      "Failed": 0,
      "Resume": false,
      "Name": "PGVF.NonSubmit.Action"
  },
  {
    "Failed": 0,
    "Resume": false,
    "Name": "PGVF.NonSubmit.Action"
  },
];

const array2 = [
  {
    "Name": "NonSubmit"
  },
  {
      "Name": "NonPermit"
  },
]

function solution() {
  return array1.filter((item1) => {
    let flag = false
    array2.forEach(item2 => {
      if (item1.Name.includes(item2.Name)) {
        flag = true
      }
    })
    return flag
  })
}

console.log(solution())

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10193

Using Array.prototype.some, you can check if Name value on arr1 item contains the arr2 item or not.

And based on that some() result, using Array.prototype.filter, you can filter the arr1 items by arr2 items.

const arr1 = [{
    "Failed": 0,
    "Resume": false,
    "Name": "GRP.Compiled.Release"
},
{
    "Failed": 0,
    "Resume": false,
    "Name": "GPST.NonPermit.Inacitve"
},
{
    "Failed": 0,
    "Resume": false,
    "Name": "PGVF.NonSubmit.Action"
},
{
   "Failed": 0,
   "Resume": false,
   "Name": "PGVF.NonSubmit.Action"
}];

const arr2 = [{
    "Name": "NonSubmit"
}, {
    "Name": "NonPermit"
}];

const output = arr1.filter(({ Name }) => arr2.some((item) => Name.includes(item.Name)));
console.log(output);

Upvotes: 3

Related Questions