JavaScriptでのサブ配列のマージ
このような一部の人の名前と電子メールに関する情報を含む配列の配列があるとします-
const arr = [ ["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"] ];
配列の各要素は文字列のサブ配列であり、最初の要素は名前であり、残りの要素はその名前に属する電子メールです。
ここで、これらのサブ配列をマージします。両方のサブアレイに共通する電子メールがある場合、2つのサブアレイは間違いなく同じ人物に属します。
2つのサブ配列が同じ名前であっても、同じ名前を持つ可能性があるため、異なる人に属している可能性があることに注意してください。
最初は任意の数のアカウントを持つことができますが、すべてのアカウントは間違いなく同じ名前です。
サブアレイをマージした後、次の形式で返す必要があります。各サブアレイの最初の要素は名前であり、残りの要素は並べ替えられた順序の電子メールです。サブアレイ自体は任意の順序で返すことができます。
したがって、上記の配列の場合、出力は次のようになります-
const output = [ ["John", '[email protected]', '[email protected]', '[email protected]'], ["John", "[email protected]"], ["Mary", "[email protected]"] ];
例
このためのコードは-
になりますconst arr = [ ["John", "[email protected]", "[email protected]"], ["John", "[email protected]"], ["John", "[email protected]", "[email protected]"], ["Mary", "[email protected]"] ]; 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', '[email protected]', '[email protected]', '[email protected]' ], [ 'John', '[email protected]' ], [ 'Mary', '[email protected]' ] ]
-
JavaScript Let
2015年に導入されたJavaScriptLetキーワードを使用すると、ブロックスコープの変数を定義できます。 以下は、JavaScriptでLetキーワードを使用して変数を宣言するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0&
-
JavaScriptランダム
Math.random()関数は、0から1までの乱数を生成するために使用されます。 以下はMath.random()関数のコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document