Entduplizieren einzelner oder Zusammenführen und Entduplizieren mehrerer Array-Eingaben. Beispiel unten.
Verwendung von ES6 - Set, for of, Destrukturierung
Ich habe diese einfache Funktion geschrieben, die mehrere Array-Argumente akzeptiert. Tut so ziemlich das Gleiche wie die Lösung oben, nur mit mehr praktischen Anwendungsfällen. Diese Funktion nicht verketten doppelte Werte in ein Array nur, so dass es sie zu einem späteren Zeitpunkt löschen kann.
KURZE FUNKTIONSDEFINITION ( nur 9 Zeilen )
/**
* This function merging only arrays unique values. It does not merges arrays in to array with duplicate values at any stage.
*
* @params ...args Function accept multiple array input (merges them to single array with no duplicates)
* it also can be used to filter duplicates in single array
*/
function arrayDeDuplicate(...args){
let set = new Set(); // init Set object (available as of ES6)
for(let arr of args){ // for of loops through values
arr.map((value) => { // map adds each value to Set object
set.add(value); // set.add method adds only unique values
});
}
return [...set]; // destructuring set object back to array object
// alternativly we culd use: return Array.from(set);
}
BENUTZUNGSBEISPIEL CODEPEN :
// SCENARIO
let a = [1,2,3,4,5,6];
let b = [4,5,6,7,8,9,10,10,10];
let c = [43,23,1,2,3];
let d = ['a','b','c','d'];
let e = ['b','c','d','e'];
// USEAGE
let uniqueArrayAll = arrayDeDuplicate(a, b, c, d, e);
let uniqueArraySingle = arrayDeDuplicate(b);
// OUTPUT
console.log(uniqueArrayAll); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 43, 23, "a", "b", "c", "d", "e"]
console.log(uniqueArraySingle); // [4, 5, 6, 7, 8, 9, 10]