@ashenm/

Symmetric Difference

JavaScript

Specimen code solution for freeCodeCamp advanced algorithm scripting challenge.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Symmetric Difference
 * https://www.freecodecamp.org/challenges/symmetric-difference
 * Returns symmetric difference of two or more arrays
 *
 * Ashen Gunaratne
 * [email protected]
 *
 */

function sym(args) {
  argv = Array.from(arguments).reduce(diffArray);
  return argv.filter((element, index, array) => index === array.indexOf(element));
}

/**
 * Returns symmetric difference of two arrays
 */
function diffArray(arr1, arr2) {
  return arr1
    .filter(element => !arr2.includes(element))
    .concat(arr2.filter(element => !arr1.includes(element)));
}

// test here
sym([1, 2, 3], [5, 2, 1, 4]);
Native Browser JavaScript