Saturday, July 25, 2026
HomeLanguagesJavascriptCollect.js union() Method

Collect.js union() Method

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"}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6903 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6972 POSTS0 COMMENTS