Comment fusionner deux tableaux en JavaScript et dédoubler les éléments

Mots clés : javascriptarraysmergejavascript

meilleur 5 Réponses Comment fusionner deux tableaux en JavaScript et dédoubler les éléments

vote vote

95

var array1 = ["Vijendra", "Singh"]; var array2 = ["Singh", "Shakya"];  console.log(array1.concat(array2));
const array1 = ["Vijendra","Singh"]; const array2 = ["Singh", "Shakya"]; const array3 = [...array1, ...array2]; 
Array.prototype.unique = function() {     var a = this.concat();     for(var i=0; i<a.length; ++i) {         for(var j=i+1; j<a.length; ++j) {             if(a[i] === a[j])                 a.splice(j--, 1);         }     }      return a; }; 
var array1 = ["Vijendra","Singh"]; var array2 = ["Singh", "Shakya"]; // Merges both arrays and gets unique items var array3 = array1.concat(array2).unique();  
function arrayUnique(array) {     var a = array.concat();     for(var i=0; i<a.length; ++i) {         for(var j=i+1; j<a.length; ++j) {             if(a[i] === a[j])                 a.splice(j--, 1);         }     }      return a; }  var array1 = ["Vijendra","Singh"]; var array2 = ["Singh", "Shakya"];     // Merges both arrays and gets unique items var array3 = arrayUnique(array1.concat(array2)); 
Object.defineProperty(Array.prototype, 'unique', {     enumerable: false,     configurable: false,     writable: false,     value: function() {         var a = this.concat();         for(var i=0; i<a.length; ++i) {             for(var j=i+1; j<a.length; ++j) {                 if(a[i] === a[j])                     a.splice(j--, 1);             }         }          return a;     } }); 
vote vote

84

console.log(_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
vote vote

80

var a = [1, 2, 3], b = [101, 2, 1, 10]  var c = a.concat(b)  var d = c.filter((item, pos) => c.indexOf(item) === pos)    console.log(d) // d is [1, 2, 3, 101, 10]
var a = [1, 2, 3], b = [101, 2, 1, 10]  var c = a.concat(b.filter((item) => a.indexOf(item) < 0))    console.log(c) // c is [1, 2, 3, 101, 10]
vote vote

64

[...array1,...array2] //   =>  don't remove duplication  
[...new Set([...array1 ,...array2])]; //   => remove duplication 
vote vote

58

const input = [    [1, 2, 3],    [101, 2, 1, 10],    [2, 1]  ];  const mergeDedupe = (arr) => {    return [...new Set([].concat(...arr))];  }    console.log('output', mergeDedupe(input));

Questions similaires