Array union

JavaScript, Array · Oct 22, 2020

Returns every element that exists in any of the two arrays at least once.

  • Create a Set with all values of a and b and convert it to an array.
const union = (a, b) => Array.from(new Set([...a, ...b]));

union([1, 2, 3], [4, 3, 2]); // [1, 2, 3, 4]

More like this

  • JavaScript Array Set Operations

    Learn how to apply mathematical set operations to JavaScript arrays.

    Collection · 12 snippets

  • Array union based on function

    Returns every element that exists in any of the two arrays at least once, using a provided comparator function.

    JavaScript, Array · Oct 22, 2020

  • Mapped array union

    Returns every element from both arrays that exists at least once after applying the provided function.

    JavaScript, Array · Oct 22, 2020

  • Mapped array intersection

    Returns the elements that exist in both arrays, after applying the provided function to each array element of both.

    JavaScript, Array · Oct 20, 2020