Tutorialspoint

1 Answer
vineeth.mariserla

_.union()

_.Union() method belongs to underscore.js a library of javascript. The _.union() function is used to take n number of arrays and return a new array with the unique terms in all those arrays (union of all array). It scrutinizes each and every value of the arrays and pushes out unique values into another array.

syntax

_.union( array1, array2, .... );

Example

In the following example, _.union() is used to get an array of unique elements.

Live Demo

<html>
<body>
<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>

Output

1,2,9,40,20,3

The arrays can consist of not only numbers or strings but also empty strings or falsy values. 

Example

In the following example, all kinds of values are used in arrays. Even though, _.union() has done its task of giving a new array with unique values.

Live Demo

<html>
<body>
<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>

Output

hello,2,hi,1,,the,,,*
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.