How to remove duplicate elements from an array using Lodash

Overview

We can remove duplicate elements from an array using the _.uniq() method of Lodash. This method keeps the first instance of an element and removes the remaining one. Therefore, the order of an element in the resultant array depends on its occurrence in the array.

Syntax

_.uniq(array);
Syntax of _.uniq()

Parameters

This method accepts array to be inspected.

    Return value

    This method returns a new array that does not have any duplicates.

    Example

    Let’s take a look at an example of the _.uniq() method:

    Console

    Explanation

    In the HTML tab:

    • Line 5: We import the lodash script.

    In the JavaScript tab:

    • Line 2: We create an array and initialize it with a few values.
    • Line 5: We remove the duplicate values from the array using the _.uniq() method.
    • Line 8: We print the result to the console.