Mina Fawzy
Mina Fawzy

Reputation: 21452

How can I join two different arrays with condition?

I have two arrays with data below I need to alter the state in the first one to get all status in arr2 without duplication I have provided a sample but this not sufficient at all

const arr1 = [{ agentId: 1234, state: "CA" }];
  const arr2 = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }];
  var res = [];
  arr1.forEach((x) => {
    arr2.forEach((y) => {
      if (x.agentId === y.agentId) {
        for (const [key, value] of Object.entries(y)) {
          if (value === "c") {
            x.state += " ," + key;
          }
        }
      }
    });
  });

the result should be like that

arr1 = [{ agentId: 1234, state: "CA, AK" }]

Upvotes: 1

Views: 56

Answers (2)

kol
kol

Reputation: 28688

You can use a Set to ensure uniqueness:

const arr1 = [
  { agentId: 1234, state: "CA" },
  { agentId: 4567, state: "FL" }
];
const arr2 = [
  { agentId: 1234, AK: "c", AL: "N", CA: "c" },
  { agentId: 4567, AK: "N", AL: "c", FL: "c" }
];

for (const x of arr1) {
  const states = new Set([x.state]);
  for (const y of arr2) {
    if (x.agentId === y.agentId) {
      for (const [key, value] of Object.entries(y)) {
        if (value === "c") {
          states.add(key);
        }
      }
      break;
    }
  }
  x.state = [...states].join(", ");
}

Upvotes: 1

KooiInc
KooiInc

Reputation: 122906

You can use Array.reduce (and Array.find within it to find a matching agentId). Something like:

const arr1 = [{ agentId: 1234, state: "CA" }];
const arr2 = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }];

const arrCombined = arr1.reduce( (acc, val) => {
  const arr2Match = arr2.find(v => v.agentId === val.agentId);
  if (arr2Match) {
    return [...acc, {...val, ...arr2Match} ];
  }
  return acc;
}, []);

console.log(arrCombined);

Upvotes: 2

Related Questions