Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save edouardmisset/02c241cc84bde5273633876614197c42 to your computer and use it in GitHub Desktop.
Save edouardmisset/02c241cc84bde5273633876614197c42 to your computer and use it in GitHub Desktop.
This code snippet defines a function called `uniqueElements` that takes an array of arrays as input

Find Unique Elements from Array (symmetricDifference)

Preview:
/**
 * Returns the unique elements from n arrays.
 *
 * This function uses the `setDifference` function to find the elements that are in one array but not in the others.
 * It uses the `reduce` method to apply this process to each array in turn, starting with the first two arrays and then using their symmetric difference as the starting point for the next call.
 *
 * @template T The type of the elements in the arrays. It can be any type.
 *
 * @param {...T[][]} arrays The arrays to find the unique elements of.
 *
 * @returns {T[]} An array that contains all elements that are in exactly one of the input arrays.
 *
 * @example
 * const array1 = [1, 2, 3];
 * const array2 = [2, 3, 4];
 * const array3 = [3, 4, 5];
 * const result = uniqueElements(array1, array2, array3); // [1, 5]
 */
export const uniqueElements = <T>(...arrays: T[][]): T[] =>
  arrays.reduce((previousArray, currentArray) => [
    ...uniqueInFirst(previousArray, currentArray),
    ...uniqueInFirst(currentArray, previousArray),
  ])
export const symmetricDifference = uniqueElements
Associated Context
Type Code Snippet ( .ts )
Associated Tags uniqueElements function setDifference method reduce method symmetric difference starting point unique elements input arrays result variable previousArray array currentArray
💡 Smart Description This code snippet defines a function called uniqueElements that takes an array of arrays as input. It uses the setDifference method to find all elements in one array but not in others, and then using their symmetric difference as the starting point for
🔎 Suggested Searches JavaScript function to find unique elements from n arrays
How to use setDifference and reduce in JavaScript for array manipulation
Code snippet that returns unique elements of an array with symmetric difference using SetDifference method
Example code by applying a process to each array into the first two or others. Using Reduce method to apply a process to each array
Related Links https://www.geeksforgeeks.org/
https://www.geeksforgeeks.org/typescript-class/
https://www.geeksforgeeks.org/data-structures/linked-list/
Related People Edouard
Sensitive Information No Sensitive Information Detected
Shareable Link https://edouardmisset.pieces.cloud/?p=95bc42b294
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment