つの配列をマージし、JavaScriptの配列から重複を削除するには?


Originally posted here!
Jump to the full solution →

ステップ1 :二つの配列をマージする
JavaScriptの2つの配列をマージするには、concat() 配列メソッド.
この2つの配列を、配列の両方で繰り返していくつかの数字を考えます.
// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];
まず、この配列をconcat() メソッドarr1 このように配列.
// arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [3, 4, 5, 6, 7];

// merge arrays
// using the concat() method
// concat() method returns a new array
const arr3 = arr1.concat(arr2);

console.log(arr3); // [1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
  • The concat() メソッドは、マージ後に新しい配列を返します.

  • ステップ2 :重複した要素を配列から削除する
    配列をマージした後に、新しい配列の要素を複製していることがわかります.
    さあ、使いましょう Set() 重複または繰り返し要素を削除するコンストラクタ関数.
    では、新しい配列を渡しましょうarr3 このような関数への引数として
    // arrays
    const arr1 = [1, 2, 3, 4, 5];
    const arr2 = [3, 4, 5, 6, 7];
    
    // merge arrays
    // using the concat() method
    // concat() method returns a new array
    const arr3 = arr1.concat(arr2);
    
    const uniqueElements = new Set(arr3);
    
    今、私たちがしなければならないのは、拡散演算子を使うことです... ) setコレクションから一意の要素を新しい配列に展開します.
    こうすることができます.
    // arrays
    const arr1 = [1, 2, 3, 4, 5];
    const arr2 = [3, 4, 5, 6, 7];
    
    // merge arrays
    // using the concat() method
    // concat() method returns a new array
    const arr3 = arr1.concat(arr2);
    
    // use Set() constructor function
    // to remove duplicate or repaeted elements
    const uniqueElements = new Set(arr3);
    
    // use the spread operator ...
    // to extract values from Set collection
    // to an array
    const uniqueValArr = [...uniqueElements];
    
    console.log(uniqueValArr); // [1, 2, 3, 4, 5, 6, 7]
    
    ああ!私たちはうまく2つの配列を合併して、配列から複製要素を取り除きました.😃

    The above code can be further reduced like this,

    // arrays
    const arr1 = [1, 2, 3, 4, 5];
    const arr2 = [3, 4, 5, 6, 7];
    
    // merge arrays
    // using the concat() method
    // and use the Set() constructor function to get unique values
    // and use the spread operator to extract unique values to an array
    const uniqueValArr = [...new Set(arr1.concat(arr2))];
    
    console.log(uniqueValArr); // [1, 2, 3, 4, 5, 6, 7]
    
    See this example live in JSBin .

    お気軽に共有する場合は、この便利な発見😃.