Create an array of unique values, in order, from the input arrays
—
Array Union creates an array of unique values, in order, from the input arrays. It provides a simple, efficient utility function that flattens multiple arrays and removes duplicates while preserving the order of first occurrence.
npm install array-unionES modules (recommended for modern environments):
import arrayUnion from "array-union";TypeScript:
import arrayUnion from "array-union";
// or
import arrayUnion = require("array-union");CommonJS:
const arrayUnion = require("array-union");import arrayUnion from "array-union";
// Basic array union
arrayUnion([1, 1, 2, 3], [2, 3]);
//=> [1, 2, 3]
// Single array deduplication
arrayUnion(['foo', 'foo', 'bar']);
//=> ['foo', 'bar']
// Multiple arrays with different types
arrayUnion(['🐱', '🦄', '🐻'], ['🦄', '🌈']);
//=> ['🐱', '🦄', '🐻', '🌈']
// Complex example with multiple arrays
arrayUnion(['🐱', '🦄'], ['🐻', '🦄'], ['🐶', '🌈', '🌈']);
//=> ['🐱', '🦄', '🐻', '🐶', '🌈']Creates an array of unique values from any number of input arrays, preserving order of first occurrence.
/**
* Create an array of unique values, in order, from the input arrays
* @param arguments - Any number of arrays to union
* @returns Array containing unique values from all input arrays
*/
function arrayUnion<ArgumentsType extends readonly unknown[]>(
...arguments: readonly ArgumentsType[]
): ArgumentsType;Parameters:
...arguments: Rest parameter accepting any number of arrays. Can be mixed types (numbers, strings, objects, etc.)Returns:
Behavior:
Import Notes:
"type": "module" in package.json)arrayUnion functionUsage Examples:
// Numbers
arrayUnion([1, 2, 2, 3, 1, 2, 4], [1, 2, 3, 6, 7]);
//=> [1, 2, 3, 4, 6, 7]
// Mixed types
arrayUnion([1, 2, 2, 3, 1, 2, 4], ['c', 'a', 'd']);
//=> [1, 2, 3, 4, 'c', 'a', 'd']
// Strings only
arrayUnion(['a', 'a', 'b', 'a'], ['c', 'a', 'd']);
//=> ['a', 'b', 'c', 'd']
// Empty input
arrayUnion();
//=> []
// Single array deduplication
arrayUnion([1, 1, 2, 2, 3]);
//=> [1, 2, 3]