JavaScript Sort Objects by Property

 Sorting an array of objects by their property value

Basic of this post:

var: var is a keyword in the javascript language and used to declare a variable in function.

keys(): This is a function of the Object class of the javascript language. The Object class is also considered the package of the language. The keys() function especially receive one or more parameter for the key value to set in the object class of a newly defined object for the user.
Hierarchy of the object class:
Object.keys().sort()
Package.class().function()

sort(): This is a built-in function of the variable class in javascript language. Generally, this function is used to sort an array by default ascending order.

Anonymous function: In every object-oriented programming language, there is a special property for the class which is known as anonymous function or class. It is also known as 'function or class without a name'. This is used for the programmer for an instance function which will be used for the once. example:

sort(function(a,b)

{

    return ProgrammingLanguage[a]-ProgrammingLanguage[b]

})


return: This keyword is used to return a variable based on the function prototype.

reverse(): This is also a built-in function just like the sort() function but serves against the sort() function. The reverse() function sorts an array in descending order.

console.log: A print function used to give the output in the console of a browser.

//Body of the code

var ProgrammingLanguage = {"Python": 70

                           "C": 90

                           "C++": 80

                           "JavaScript": 100};

Sorted = Object.keys(ProgrammingLanguage).sort(function(a,b)

{

    return ProgrammingLanguage[a]-ProgrammingLanguage[b]

})


//Printing in ascending order

console.log(Sorted); 

//Printing in descending order

console.log(Sorted.reverse())



//End of the code

Sample Input:

"Python": 70, "C": 90, "C++": 80, "JavaScript": 100

Sample Output:

"Python", "C++", "C", "JavaScript"   //Asc

"JavaScript", "C", "C++", "Python" //Desc


Post a Comment

Previous Post Next Post