Array union

OSCC · 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]

Recommended snippets & collections

  • JavaScript Array Tricks

    Snippet collection

    Learn a handful of awesome tips and tricks that you can leverage in your code to make array manipulation a breeze.

  • Mapped array union

    JavaScript, Array

    Returns every element that exists in any of the two arrays at least once, after applying the provided function to each array element of both.

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

  • Partition array in two

    JavaScript, Array

    Groups the elements into two arrays, depending on the provided function's truthiness for each element.