Home > front end >  Filter 2 arrays to check if parent child
Filter 2 arrays to check if parent child

Time:10-14

I have first array -

let parent = [
    {
     id:1,
     value:"ABC",
    },
    {
     id:2,
     value:"DEF",
    },
    {
     id:3,
     value:"GHI",
    },
    {
     id:4,
     value:"JKL",
    },
    {
     id:5,
     value:"MNO",
    },
    {
     id:6,
     value:"PQR",
    },
    ]

And 2nd Array Object -

let child = [
{
 childid:1,
 value:"ABC",
},
{
 childid:2,
 value:"DEF",
},
{
 childid:10,
 value:"GHI",
},
]

From parent array I want to select all those elements whose id matches with childid from child array.

I tried -

parent.filter(x=>x.id==child.each(y=>y.childid))

But its not working

CodePudding user response:

You can use some() to do it

let parent = [
    {
     id:1,
     value:"ABC",
    },
    {
     id:2,
     value:"DEF",
    },
    {
     id:3,
     value:"GHI",
    },
    {
     id:4,
     value:"JKL",
    },
    {
     id:5,
     value:"MNO",
    },
    {
     id:6,
     value:"PQR",
    },
    ]
 
 let child = [
{
 childid:1,
 value:"ABC",
},
{
 childid:2,
 value:"DEF",
},
{
 childid:10,
 value:"GHI",
},
]


let result = parent.filter(p => child.some(a =>  a.childid == p.id ))
console.log(result)

CodePudding user response:

using Flatmap and filter ...

let parent = [{
    id: 1,
    value: "ABC",
  },
  {
    id: 2,
    value: "DEF",
  },
  {
    id: 3,
    value: "GHI",
  },
  {
    id: 4,
    value: "JKL",
  },
  {
    id: 5,
    value: "MNO",
  },
  {
    id: 6,
    value: "PQR",
  },
]
let child = [{
    childid: 1,
    value: "ABC",
  },
  {
    childid: 2,
    value: "DEF",
  },
  {
    childid: 10,
    value: "GHI",
  },
]
const res = parent.flatMap(x => child.filter(y => y.childid === x.id))
console.log(res)

CodePudding user response:

This would work

parent.filter(p => child.some(c => c.childid === p.id))

Wat happens is

  1. For each element in parent array, find the corresponding element in the child array
  2. If it exists the filter will see it as truthy and keep the parent element, if not it will be falsy and filter wil discard it

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

CodePudding user response:

const filterResult = parent.filter(x => child.some(y => y.childid == x.id))
  • Related