Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.union() Array Method

Posted in lodash Tutorial
Updated on Nov 22, 2024
By Mari Selvan
👁️ 61 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.union() Array Method

Photo Credit to CodeToFun

🙋 Introduction

Efficiently managing arrays is a common challenge in JavaScript development. Lodash, a powerful utility library, provides a wide array of functions to simplify these tasks. Among them is the _.union() method, a versatile tool for creating a unique array that contains elements from all given arrays. This method proves invaluable when dealing with diverse datasets or merging arrays without duplicates.

🧠 Understanding _.union()

The _.union() method in Lodash combines multiple arrays into a new array, excluding duplicate elements. This ensures that the resulting array only contains unique values, making it a reliable choice for array merging operations.

💡 Syntax

syntax.js
Copied
Copy To Clipboard
_.union([arrays])
  • arrays: The arrays to process.

📝 Example

Let's explore a practical example to illustrate the functionality of _.union():

example.js
Copied
Copy To Clipboard
const _ = require('lodash');

const array1 = [1, 2, 3];
const array2 = [2, 3, 4, 5];
const array3 = [4, 5, 6];

const combinedArray = _.union(array1, array2, array3);

console.log(combinedArray);
// Output: [1, 2, 3, 4, 5, 6]

In this example, _.union() merges three arrays (array1, array2, and array3) into a new array containing unique elements.

🏆 Best Practices

  1. Understanding Order Matters:

    The order of arrays passed to _.union() affects the order of elements in the resulting array. Elements from later arrays override those from earlier arrays.

    example.js
    Copied
    Copy To Clipboard
    const array1 = [1, 2, 3];
    const array2 = [2, 3, 4, 5];
    const array3 = [4, 5, 6];
    
    const combinedArray1 = _.union(array1, array2, array3);
    const combinedArray2 = _.union(array3, array2, array1);
    
    console.log(combinedArray1);
    // Output: [1, 2, 3, 4, 5, 6]
    
    console.log(combinedArray2);
    // Output: [6, 5, 4, 2, 3, 1]
  2. Handling Arrays of Objects:

    When working with arrays of objects, use the iteratee function to specify how object uniqueness is determined.

    example.js
    Copied
    Copy To Clipboard
    const array1 = [{ id: 1, name: 'Alice' }];
    const array2 = [{ id: 2, name: 'Bob' }, { id: 1, name: 'Alice' }];
    
    const combinedArray = _.unionWith(array1, array2, _.isEqual);
    
    console.log(combinedArray);
    // Output: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
  3. Utilizing _.unionWith():

    For more control over the comparison of elements, consider using _.unionWith() and providing a custom comparator function.

    example.js
    Copied
    Copy To Clipboard
    const array1 = [{ id: 1, name: 'Alice' }];
    const array2 = [{ id: 2, name: 'Bob' }, { id: 1, name: 'Alice' }];
    
    const combinedArray = _.unionWith(array1, array2, (a, b) => a.id === b.id);
    
    console.log(combinedArray);
    // Output: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]

📚 Use Cases

  1. Merging Arrays Without Duplicates:

    The primary use case for _.union() is merging arrays while excluding duplicate elements, ensuring a clean and unique result.

    example.js
    Copied
    Copy To Clipboard
    const userArray = [101, 102, 103];
    const adminArray = [102, 103, 104, 105];
    const moderatorArray = [103, 104, 105, 106];
    
    const combinedRoles = _.union(userArray, adminArray, moderatorArray);
    
    console.log(combinedRoles);
    // Output: [101, 102, 103, 104, 105, 106]
  2. User Preferences or Settings:

    When dealing with user preferences or settings stored in arrays, _.union() can be employed to merge these arrays and ensure that only distinct preferences are retained.

    example.js
    Copied
    Copy To Clipboard
    const user1Preferences = ['dark-mode', 'font-size'];
    const user2Preferences = ['light-mode', 'font-size', 'language'];
    
    const mergedPreferences = _.union(user1Preferences, user2Preferences);
    
    console.log(mergedPreferences);
    // Output: ['dark-mode', 'font-size', 'light-mode', 'language']
  3. Unique Values from Multiple Sources:

    In scenarios where data comes from multiple sources, _.union() proves useful for creating a consolidated array of unique values.

    example.js
    Copied
    Copy To Clipboard
    const dataSource1 = [10, 20, 30];
    const dataSource2 = [20, 30, 40, 50];
    const dataSource3 = [30, 40, 50, 60];
    
    const uniqueValues = _.union(dataSource1, dataSource2, dataSource3);
    
    console.log(uniqueValues);
    // Output: [10, 20, 30, 40, 50, 60]

🎉 Conclusion

The _.union() method in Lodash provides an effective solution for merging arrays without duplicates. Whether you're consolidating user roles, preferences, or data from various sources, this method offers simplicity and reliability in array manipulation.

Explore the versatility of _.union() and elevate your JavaScript development experience by efficiently handling arrays with unique values!

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy