Intermediate Algorithm Scripting Flashcards
Diff Two Arrays
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
(CODE)
function diffArray(arr1, arr2) { return arr1 .concat(arr2) .filter(item => !arr1.includes(item) || !arr2.includes(item)); }
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]); //returns 4
Seek and Destroy
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
Note
You have to use the arguments object.
(CODE)
function destroyer(arr) { var args = Array.from(arguments).slice(1); return arr.filter(function(val) { return !args.includes(val); }); }
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // [1,1]
Get an array of object keys
var keys = Object.keys(obj);
Euclidean algorithm, which is used for finding smallest common multiples
function gcd(x, y) { // Implements the Euclidean Algorithm if (y === 0) return x; else return gcd(y, x % y); }