Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Gộp các mảng con theo email chung trong JavaScript

Cho mảng các mảng con [name, email1, email2...]. Gộp các mảng con có chung email (union-find). Kết quả: mỗi nhóm [name, emails...] với emails sắp xếp.

Ví dụ

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));

Kết quả

[    [       'John',       'john00@mail.com',       'john_newyork@mail.com',       'johnsmith@mail.com'    ],    [ 'John', 'johnnybravo@mail.com' ],    [ 'Mary', 'mary@mail.com' ] ]