Skip to main content

How get unique and sorted values from an array using JavaScript?

Get unique and sorted values from an array in JavaScript:-

// Array need to make unique and sorted
var Cities = ['Kolkata', 'Udaipur', 'Delhi', 'Mumbai', 'Chennai', 'Hyderabad', 'Bangalore','Chennai','Delhi','Mumbai'];

Method 1:

//an empty array declared
let UniqueSortedCities = [];
//loop use to iterate items of array
Cities.forEach(function(c){
    if(UniqueSortedCities.indexOf(c) == -1){ //using indexOf() method checking the values present in array
       UniqueSortedCities.push(c);  // Using push() method we can add item/city in an array.
    }
});
//Using sort method we can sort an array.
console.log(UniqueSortedCities.sort());
Output:
["Bangalore", "Chennai", "Delhi", "Hyderabad", "Kolkata", "Mumbai", "Udaipur"]; //unique and sorted array.

Method 2:

let UniqueSortedCities = [];
Cities.forEach(function(c){
    if(!UniqueSortedCities.includes(c)){
       UniqueSortedCities.push(c);
    }
});
//Using sort method we can sort an array.
console.log(UniqueSortedCities.sort());
Output:
 ["Bangalore", "Chennai", "Delhi", "Hyderabad", "Kolkata", "Mumbai", "Udaipur"]

Method 3:

let UniqueSortedCities = [];
var obj={};
Cities.forEach(function(c){
   obj[c] = [c];
});
Object.keys(obj).sort().forEach(function(ct){
   UniqueSortedCities.push(ct);
});
//Using sort method we can sort an array.
console.log(UniqueSortedCities.sort());
Output:
["Bangalore", "Chennai", "Delhi", "Hyderabad", "Kolkata", "Mumbai", "Udaipur"]

Comments

Popular posts from this blog

How to send email using SharePoint REST API in jQuery/JavaScript?

  Send email using SharePoint REST API in jQuery/JavaScript: We can able to send email to the SharePoint user using below REST API on SharePoint Online. We need to load SP.js file in code. we must need to give valid SharePoint user to send email. We can able to send email to valid SharePoint user of same organization.      var   restAPI  =  _spPageContextInfo . webAbsoluteUrl  +  "/_api/SP.Utilities.Utility.SendEmail" ;      $ . ajax ({          contentType:   'application/json' ,          url:   restAPI ,          type:   "POST" ,          data:   JSON . stringify ({              'properties' :  {             ...

How to get all site users of SharePoint using REST API?

Get all users of SharePoint site using REST API: These users and its data are required to update people field of a SharePoint list. By using below snippet code we can able to get details of a user of SharePoint site.     var webURL = _spPageContextInfo.webAbsoluteUrl+"/_api/Web/SiteUsers";         $.ajax({           url: customFieldURL,           method: "GET",           headers: {             "Accept": "application/json; odata=verbose"           },           success: function (data) {            console.log(data);             data.d.results.forEach(function(cm){                     console.log(cm.Title+" - "+cm.Email+" - "+cm.Id);             });      ...