skip to Main Content

I need to remove an nested array if it matches the id of the main array.

arrayOne =

[
    {
        "id": "1",
        "role": [
            "pos_cashier_1",
            "pos_manager"
        ]
    },
    {
        "id": "2",
        "role": [
            "pos_manager",
            "pos_cashier_2"
        ]
    }
]

arrayTwo

[
    {
        "label": "Sessions Sandringham",
        "value": "1"
    },
    {
        "label": "Sessions West Brunswick",
        "value": "2"
    },
    {
        "label": "Global",
        "value": null
    }
]

I need to remove the arrays in the arrayTwo if its value == id in the arrayOne.
Can someone help me…

4

Answers


  1. You can first create a Set of all the ids in the first array, then filter the second array based on the existence of the value property in that Set.

    let arr1=[{id:"1",role:["pos_cashier_1","pos_manager"]},{id:"2",role:["pos_manager","pos_cashier_2"]}],arr2=[{label:"Sessions Sandringham",value:"1"},{label:"Sessions West Brunswick",value:"2"},{label:"Global",value:null}];
    let ids = new Set(arr1.map(o => o.id));
    let res = arr2.filter(x => !ids.has(x.value));
    console.log(res);
    Login or Signup to reply.
  2. It’s more efficient to create a set of ids first, but you can also do it as a one-liner using find like this:

    const arr1 = [{"id":"1","role":["pos_cashier_1","pos_manager"]},{"id":"2","role":["pos_manager","pos_cashier_2"]}]
    const arr2 = [{"label":"Sessions Sandringham","value":"1"},{"label":"Sessions West Brunswick","value":"2"},{"label":"Global","value":null}]
    
    console.log(arr2.filter(({value:v})=>!arr1.some(({id})=>id===v)))
    Login or Signup to reply.
  3. You can also do using find and filter

    const arr1 = [{"id":"1","role":["pos_cashier_1","pos_manager"]},{"id":"2","role":["pos_manager","pos_cashier_2"]}]
    const arr2 = [{"label":"Sessions Sandringham","value":"1"},{"label":"Sessions West Brunswick","value":"2"},{"label":"Global","value":null}]
    
    let output = arr2.filter(d => d.value == arr1.find(info => info.id == d.value))
    
    console.log(output)
    
    Login or Signup to reply.
  4. You can use filter and some like this:

    const arrayOne = [
      {
        "id": "1",
        "role": [
          "pos_cashier_1",
          "pos_manager"
        ]
      },
      {
        "id": "2",
        "role": [
          "pos_manager",
          "pos_cashier_2"
        ]
      }
    ];
    
    const arrayTwo = [
      {
        "label": "Sessions Sandringham",
        "value": "1"
      },
      {
        "label": "Sessions West Brunswick",
        "value": "2"
      },
      {
        "label": "Global",
        "value": null
      }
    ];
    const filtered = arrayTwo.filter(({ value }) => !arrayOne.some(({ id }) => id === value));
    console.log(filtered)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search