Skip to content
Related Articles

Related Articles

Collect.js union() Method

Improve Article
Save Article
Like Article
  • Last Updated : 14 Dec, 2020

The union() method is used to add the given array to the collection with the unique values. If the given array contains values that are already in the original collection, the original collection’s values will be preferred.

Syntax:

collect.union()

Parameters: The collect() method takes one argument that is converted into the collection and then union() method is applied on it.

Return Value: This method returns the collection with the unique elements.

Below example illustrate the union() method in collect.js:

Example 1:




const collect = require('collect.js'); 
    
let obj = [1, 2, 3, 4, 5]; 
    
const collection = collect(obj); 
  
const union = collection.union([1, 2, 3, 2, 4]); 
    
console.log(union.all());

Output:

[1, 2, 3, 4, 5]

Example 2:




const collect = require('collect.js');
  
let obj = ({
    name1: 'AAA',
    name2: 'BBB',
});
  
const collection = collect(obj);
  
const union = collection.union({
    name1: 'AAAAA',
    name3: 'CCCCC',
    name2: 'BBBBB',
});
  
console.log(union.all());

Output:

{name1: "AAA", name2: "BBB", name3: "CCCCC"}
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!