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"]
// 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
Post a Comment