다음과 같은 사람들의 이름과 이메일에 대한 정보를 포함하는 배열 배열이 있다고 가정해 보겠습니다.
const arr = [ ["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"] ];
배열의 각 요소는 문자열의 하위 배열로, 첫 번째 요소는 이름이고 나머지 요소는 해당 이름에 속한 이메일입니다.
이제 이 하위 배열을 병합하려고 합니다. 두 하위 배열에 공통적인 이메일이 있는 경우 두 하위 배열은 분명히 같은 사람에게 속합니다.
두 하위 배열의 이름이 같더라도 사람들이 같은 이름을 가질 수 있으므로 다른 사람들에게 속할 수 있습니다.
한 사람이 처음에 원하는 수의 계정을 가질 수 있지만 모든 계정의 이름은 확실히 동일합니다.
하위 배열을 병합한 후 다음 형식으로 반환해야 합니다. 각 하위 배열의 첫 번째 요소는 이름이고 나머지 요소는 정렬된 순서의 이메일입니다. 하위 배열 자체는 임의의 순서로 반환될 수 있습니다.
따라서 위의 배열의 경우 출력은 다음과 같아야 합니다. -
const output = [ ["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"] ];
예시
이에 대한 코드는 -
const arr = [
["John", "johnsmith@mail.com", "john00@mail.com"],
["John", "johnnybravo@mail.com"],
["John", "johnsmith@mail.com", "john_newyork@mail.com"],
["Mary", "mary@mail.com"]
];
const recusiveMatch = (included, i, tmp, arr, res) => {
for(let j = 1; j < arr[i].length; j += 1) {
let currentEmail = arr[i][j];
if(included.has(currentEmail)) continue;
res.push(currentEmail);
included.add(currentEmail);
let currentAccountIndexes = tmp.get(currentEmail);
for(let c = 0; c < currentAccountIndexes.length; c += 1) {
let currentIndex = currentAccountIndexes[c];
if(i !== currentIndex) {
recusiveMatch(included, currentIndex, tmp, arr, res);
}
}
}
};
const merge = (arr) => {
const tmp = new Map(),
included = new Set(),
res = [];
arr.forEach((account, i) => {
for(let u = 1; u < account.length; u += 1) {
let currentEMail = account[u];
tmp.set(currentEMail, tmp.get(currentEMail) || []);
tmp.get(currentEMail).push(i);
}
});
arr.forEach((account, i) => {
if(!included.has(arr[1])) {
let u = [];
recusiveMatch(included, i, tmp, arr, u);
if(u.length) {
res.push(u);
u.sort();
u.unshift(account[0]);
}
}
});
return res;
};
console.log(merge(arr)); 출력
콘솔의 출력은 -
[ [ 'John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com' ], [ 'John', 'johnnybravo@mail.com' ], [ 'Mary', 'mary@mail.com' ] ]