Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.uniqBy() Array Method

Posted in lodash Tutorial
Updated on Feb 24, 2024
By Mari Selvan
👁️ 69 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.uniqBy() Array Method

Photo Credit to CodeToFun

🙋 Introduction

In the realm of JavaScript development, effective array manipulation is a fundamental aspect of creating robust applications. Lodash, a comprehensive utility library, provides a range of functions to simplify array operations. Among these functions is the _.uniqBy() method, a powerful tool for creating an array with unique values based on a specific criterion.

This method enhances code clarity and flexibility, making it essential for developers dealing with diverse datasets.

🧠 Understanding _.uniqBy()

The _.uniqBy() method in Lodash is designed to create a new array with unique values based on the result of applying an iteratee function to each element. This allows developers to define a custom criterion for uniqueness, offering precision in handling arrays with complex data structures.

💡 Syntax

syntax.js
Copied
Copy To Clipboard
_.uniqBy(array, [iteratee])
  • array: The array to process.
  • iteratee (Optional): The function invoked per iteration.

📝 Example

Let's dive into a practical example to understand the functionality of _.uniqBy():

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

const arrayWithDuplicates = [
    { id: 1, name: 'apple' },
    { id: 2, name: 'banana' },
    { id: 3, name: 'apple' },
    { id: 4, name: 'orange' },
];

const uniqueArray = _.uniqBy(arrayWithDuplicates, obj => obj.name);

console.log(uniqueArray);
// Output: [{ id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 4, name: 'orange' }]

In this example, the arrayWithDuplicates is processed by _.uniqBy(), resulting in a new array containing only unique elements based on the 'name' property.

🏆 Best Practices

  1. Define Custom Criteria:

    Leverage the iteratee parameter to define a custom criterion for uniqueness. This allows you to tailor the behavior of _.uniqBy() according to your specific requirements.

    example.js
    Copied
    Copy To Clipboard
    const arrayOfObjects = [
        { id: 1, category: 'fruit' },
        { id: 2, category: 'vegetable' },
        { id: 3, category: 'fruit' },
    ];
    
    const uniqueCategories = _.uniqBy(arrayOfObjects, obj => obj.category);
    
    console.log(uniqueCategories);
    // Output: [{ id: 1, category: 'fruit' }, { id: 2, category: 'vegetable' }]
  2. Handling Complex Objects:

    When dealing with complex objects, ensure that the iteratee function provides a unique identifier to accurately identify duplicate entries.

    example.js
    Copied
    Copy To Clipboard
    const complexObjects = [
        { id: 1, details: { type: 'A', value: 10 } },
        { id: 2, details: { type: 'B', value: 20 } },
        { id: 3, details: { type: 'A', value: 10 } },
    ];
    
    const uniqueObjects = _.uniqBy(complexObjects, obj => `${obj.details.type}-${obj.details.value}`);
    
    console.log(uniqueObjects);
    // Output: [ { id: 1, details: { type: 'A', value: 10 } }, { id: 2, details: { type: 'B', value: 20 } } ]
  3. Performance Considerations:

    Be mindful of performance when working with large datasets. While _.uniqBy() is efficient, handling massive arrays may benefit from optimization strategies.

    example.js
    Copied
    Copy To Clipboard
    const largeDataset = /* ...fetch data from API or elsewhere... */;
    
    console.time('uniqBy');
    const uniqueValues = _.uniqBy(largeDataset, 'property');
    console.timeEnd('uniqBy');
    
    console.log(uniqueValues);

📚 Use Cases

  1. Removing Duplicate Entries:

    _.uniqBy() is particularly useful when dealing with datasets containing duplicate entries. By removing duplicates, you can ensure data integrity and streamline subsequent operations.

    example.js
    Copied
    Copy To Clipboard
    const arrayWithDuplicates = [1, 2, 2, 3, 3, 4, 5, 5, 5];
    const uniqueValues = _.uniqBy(arrayWithDuplicates);
    
    console.log(uniqueValues);
    // Output: [1, 2, 3, 4, 5]
  2. Data Normalization:

    In scenarios where data normalization is necessary, _.uniqBy() can be employed to condense redundant information, facilitating cleaner and more concise data representation.

    example.js
    Copied
    Copy To Clipboard
    const dataWithDuplicates = [
        { id: 1, category: 'fruit' },
        { id: 2, category: 'vegetable' },
        { id: 3, category: 'fruit' },
        { id: 4, category: 'vegetable' },
    ];
    
    const uniqueCategories = _.uniqBy(dataWithDuplicates, 'category');
    
    console.log(uniqueCategories);
    // Output: [ { id: 1, category: 'fruit' }, { id: 2, category: 'vegetable' } ]
  3. Filtering Unique Values:

    When you need to filter an array and retain only unique values based on a specific criterion, _.uniqBy() becomes a valuable ally.

    example.js
    Copied
    Copy To Clipboard
    const products = [
        { id: 1, name: 'apple', category: 'fruit' },
        { id: 2, name: 'banana', category: 'fruit' },
        { id: 3, name: 'carrot', category: 'vegetable' },
        { id: 4, name: 'apple', category: 'fruit' },
    ];
    
    const uniqueFruits = _.uniqBy(products, 'name');
    
    console.log(uniqueFruits);
    // Output: [ { id: 1, name: 'apple', category: 'fruit' }, { id: 2, name: 'banana', category: 'fruit' }, { id: 3, name: 'carrot', category: 'vegetable' } ]

🎉 Conclusion

The _.uniqBy() method in Lodash provides an efficient solution for creating arrays with unique values based on a custom criterion. Whether you're working with simple arrays or complex data structures, this method offers versatility and clarity in array manipulation.

Harness the power of _.uniqBy() to streamline your JavaScript development and ensure data uniqueness in your applications!

👨‍💻 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