Javascript Array diffArray(arr1, arr2)
/*/*from ww w . j a va2 s.c o m*/ 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. Here are some helpful links: Comparison Operators Array.prototype.slice() Array.prototype.filter() Array.prototype.indexOf() Array.prototype.concat() */ function diffArray(arr1, arr2) { // merge arrays to new one with .concat() var newArr = arr1.concat(arr2); function checkItems(item) { if (arr1.indexOf(item) === -1 || arr2.indexOf(item) === -1) { return item; } } return newArr.filter(checkItems); } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
/*/* w w w.ja v a2 s . c o m*/ 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. Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code. Here are some helpful links: Comparison Operators Array.prototype.slice() Array.prototype.filter() Array.prototype.indexOf() Array.prototype.concat() */ function diffArray(arr1, arr2) { var newArray = arr1.concat(arr2); function symmetricDifference(val) { if (arr1.indexOf(val) < 0 || arr2.indexOf(val) < 0) { return val; } } return newArray.filter(symmetricDifference); } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
function diffArray(arr1, arr2) { let newArr1 = []; let newArr2 = []; let sliced = []; for (let y = 0; y < arr1.length; y++) { if (arr2.includes(arr1[y]) === false) { newArr1.push(y);/*w w w. ja v a2s.c om*/ } } for (let i = 0; i < newArr1.length; i++) { sliced.push(arr1.splice(newArr1[0], 1)); } for (let x = 0; x < arr2.length; x++) { if (arr1.includes(arr2[x]) === false) { newArr2.push(x); } } for (let j = 0; j < newArr2.length; j++) { sliced.push(arr2.splice(newArr2[0], 1)); } //let finalArr = [].concat(...sliced); or let finalArr = [].concat.apply([], sliced); return finalArr; //console.log(finalArr); } diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]); /* Flattening multidimensional Arrays in JavaScript http://www.jstips.co/en/flattening-multidimensional-arrays-in-javascript/ Array.prototype.slice() Array.prototype.filter() Array.prototype.indexOf() Array.prototype.concat() Array.prototype.splice() Array.prototype.includes() */