Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the importance of _.union() method in JavaScript?
The _.union() method from the Underscore.js library creates a new array containing unique values from multiple input arrays. It performs a union operation, removing duplicates while preserving the original order of first occurrence.
Syntax
_.union(array1, array2, ...arrayN);
Parameters
array1, array2, ...arrayN: Two or more arrays to be combined. The method accepts any number of arrays as arguments.
Return Value
Returns a new array containing all unique values from the input arrays, maintaining the order of first occurrence.
Example with Numbers
In the following example, _.union() combines multiple arrays and removes duplicates:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
document.write(_.union([1, 2, 9, 40],
[1, 20, 3, 2],
[9, 2]));
</script>
</body>
</html>
1,2,9,40,20,3
Example with Mixed Data Types
The method works with various data types including strings, numbers, empty values, and falsy values:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
document.write(_.union(["hello", 2, "hi", 1, ""],
['the', undefined],
['', null],
["*", ""]));
</script>
</body>
</html>
hello,2,hi,1,,the,,,*
Key Points
- Maintains the order of first occurrence from left to right
- Works with any data type including strings, numbers, objects, and falsy values
- Returns a new array without modifying the original arrays
- Uses strict equality (===) for duplicate detection
Common Use Cases
- Merging multiple arrays while avoiding duplicates
- Combining user selections from different sources
- Creating unique lists from multiple data sets
- Consolidating arrays in functional programming workflows
Conclusion
The _.union() method provides an efficient way to combine multiple arrays while ensuring uniqueness. It's particularly useful when working with data from different sources that may contain overlapping values.
