つの配列をマージし、JavaScriptの配列から重複を削除するには?
9329 ワード
Originally posted here!
Jump to the full solution →
ステップ1 :二つの配列をマージする
JavaScriptの2つの配列をマージするには、
この2つの配列を、配列の両方で繰り返していくつかの数字を考えます.
The
ステップ2 :重複した要素を配列から削除する
配列をマージした後に、新しい配列の要素を複製していることがわかります.
さあ、使いましょう
では、新しい配列を渡しましょう
こうすることができます.
See this example live in JSBin .
お気軽に共有する場合は、この便利な発見😃.
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]
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]
お気軽に共有する場合は、この便利な発見😃.
Reference
この問題について(つの配列をマージし、JavaScriptの配列から重複を削除するには?), 我々は、より多くの情報をここで見つけました https://dev.to/melvin2016/how-to-merge-two-arrays-and-remove-duplicates-from-the-array-in-javascript-11hoテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol