Yogesh Mali
Yogesh Mali

Reputation: 223

Check if an element is common between 2 arrays and then assign values from it

In my angular 8 application, I have 2 arrays:

array1 = [{
        "SubType": "2|3|4|5|6",
    },
    {
        "SubType": "2",
    },
    {
        "SubType": "3|4",
    },
    {
        "SubType": "6",
    },
    {
        "SubType": "3|6",
    },
]

&

array2 = [{
        "id": 2,
        "type": "1",
    },
    {
        "id": 3,
        "type": "5",
    },
    {
        "id": 4,
        "type": "4",
    },
    {
        "id": 5,
        "type": "3",
    },
    {
        "id": 6,
        "type": "2",
    }
]

I am trying to check each "SubType" in array1 and see if that element(id) is present in array2 and if present assign its "type" to a variable. "SubType" is | separated which I and converting to an array using array1..split('|'). This when assigning to a variable will need to be comma separated. I tried using array filter but I am not able to find a way to loop thorough the second array. Can anyone help?

array1.forEach(reg => {
    if (reg.SubType) {
        let subTypeTemp = reg.SubType.split('|');
        let tempVariable = subTypeTemp.some(ele => {
            let stringToassign = '';
            for (let i = 0; i < array2.length; i++) {
                if (ele == array2[i].id) {
                    stringToassign += array2[i].type + ",";
                }
            }
        })
    }
})

Upvotes: 0

Views: 49

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take a Map and prevent looping array2 over and over for getting type of a wanted id.

var array1 = [{ SubType: "2|3|4|5|6" }, { SubType: "2" }, { SubType: "3|4" }, { SubType: "6" }, { SubType: "3|6" }],
    array2 = [{ id: 2, type: "1" }, { id: 3, type: "5" }, { id: 4, type: "4" }, { id: 5, type: "3" }, { id: 6, type: "2" }],
    types = new Map(array2.map(({ id, type }) => [id.toString(), type])),
    result = array1.map(({ SubType }) => SubType
        .split('|')
        .map(Map.prototype.get, types)
        .join()
    );

console.log(result);

Upvotes: 2

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

const array1 = [
  {
    SubType: "2|3|4|5|6"
  },
  { SubType: "2" },
  { SubType: "3|4" },
  { SubType: "6" },
  { SubType: "3|6" }
];

const array2 = [
  {
    id: 2,
    type: "1"
  },
  { id: 3, type: "5" },
  { id: 4, type: "4" },
  { id: 5, type: "3" },
  { id: 6, type: "2" }
];

const array2Obj = array2.reduce(
  (acc, curr) => ({
    ...acc,
    [curr.id]: curr.type
  }),
  {}
);

const types = [];
array1.forEach(item => {
  const sub_types = item.SubType.split("|");
  sub_types.forEach(st => {
    if (st in array2Obj) {
      types.push(array2Obj[st]);
    }
  });
});

const types_str = [...new Set(types)].join(',');

console.log("types", types_str);

Upvotes: 2

Related Questions