Open In App

Lodash _.sortedUniq()Method

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.sortedUniq method is used to return the lowest index of the array where an element can be inserted and maintain its sorted order. Also, this method is like _.uniq except that it’s designed and optimized for sorted arrays. In _.uniq only the first occurrence of each element is kept and the order of result values is determined by the order they occur in the array.

Syntax:

_.sortedUniq(array);

Parameters:

  • array: This parameter holds the array to inspect.
  • Return Value:

    This method is used to return the new duplicate free array.

    Example 1: In this example, we are getting a unique array by the use of the lodash _.sortedUniq() method.

    javascript




    // Requiring the lodash library
    const _ = require("lodash");
         
    // Original array
    let y = ([1, 1, 2, 3, 3, 4]);
         
    // Use of  _.sortedUniq()
    // method
    let index =  _.sortedUniq(y, [1, 1, 2]);
         
    // Printing the output
    console.log(index);

    
    

    Output: 

    [ 1, 2, 3, 4 ]

    Example 2: In this example, we are getting a unique array of characters by the use of the lodash _.sortedUniq() method.

    javascript




    // Requiring the lodash library
    const _ = require("lodash");
         
    // Original array
    let y = (['p', 'q', 'r', 't', 't',
        'u', 's', 't', 't', 'v', 'w']);
         
    // Use of  _.sortedUniq()
    // method
    let index =  _.sortedUniq(y);
         
    // Printing the output
    console.log(index);

    
    

    Output:

    ['p', 'q', 'r', 't', 'u', 's', 't', 'v', 'w']

    Example 3: In this example, we are getting a unique array of strings by the use of the lodash _.sortedUniq() method.

    javascript




    // Requiring the lodash library
    const _ = require("lodash");
     
    // Original array
    let y = (['chemistry', 'computer', 'computer',
     
        'english', 'geography', 'hindi', 'hindi',
     
        'maths', 'physics']);
     
    // Use of  _.sortedUniq()
    // method
    let index = _.sortedUniq(y);
     
    // Printing the output
    console.log(index);

    
    

    Output:

    ['chemistry', 'computer', 'english', 
    'geography', 'hindi', 'maths', 'physics']

    Note: This will not work in normal JavaScript because it requires the library lodash to be installed.



    Like Article
    Suggest improvement
    Previous
    Next
    Share your thoughts in the comments

    Similar Reads