Created
July 16, 2021 02:50
-
-
Save chris-burkhardt/366b83e54eccaa8c4823eb147c817fcc to your computer and use it in GitHub Desktop.
Nodejs Distinct Array Items
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const diff = (arr1, arr2) => [ | |
...arr1.filter(e => !arr2.includes(e)), | |
...arr2.filter(e => !arr1.includes(e)) | |
]; | |
const sym = (...args) => [...new Set(args.reduce(diff))]; | |
sym([1, 2, 3], [5, 2, 1, 4]); | |
// =========================== | |
// Explanation (individually) | |
// The code above works by filtering out distinct items from each array in the diff function. Those items are then returned in a single array. Then the single array is reduced to unique items. | |
const arr2Distinct = [...[5, 2, 1, 4].filter(e => ![1, 2 ,3].includes(e))] | |
//console.log("arr2Distinct", arr2Distinct) | |
// result: [ 5, 4 ] | |
const arr1Distinct = [...[1, 2, 3].filter(e => ![5, 2, 1, 4].includes(e))] | |
//console.log("arr1Distinct", arr1Distinct) | |
// result: [ 3 ] | |
const combinedArrays = [...arr1Distinct, ...arr2Distinct] | |
//console.log("combinedArrays", combinedArrays) | |
// result: [ 3, 4, 5 ] | |
// dedupe the arrays | |
const dedupedArrays = [...new Set(combinedArrays)] | |
///console.log("dedupedArrays: ", dedupedArrays) | |
References: | |
// ...args spreads the args | |
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax | |
// https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-find-the-symmetric-difference/301611a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment