Skip to main content

Sorting an array of objects using Javascript

 When working on one of my projects, I had to sort the elements of the JSON array of objects. I did this most of the time from server side but this time I had to do the client side sort.

Here is the solution what I found.

We've two functions one to sort by ascending and other for descending. It expects first parameter as array (of objects) and second parameter the key on basis of which we want to sort.

 
<script>
function sortByKeyDesc(array, key) {
	return array.sort(function (a, b) {
    	var x = a[key]; var y = b[key];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
	});
}

function sortByKeyAsc(array, key) {
	return array.sort(function (a, b) {
    	var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	});
}
</script>
Here is the example

<script>
books = [{
  'BookID': 123,
  'BookName': 'Seven Habits of most effective people'
}, {
  'BookID': 234,
  'BookName': 'Why Leaders eat last'
}, {
  'BookID': 345,
  'BookName': 'How to influence people'
}, {
  'BookID': 456,
  'BookName': 'The Tipping point'
}];

sorted_books = sortByKeyAsc(books, 'BookName');
console.log(sorted_books);
</script>
Result will be

[{
  BookID: 345,
  BookName: "How to influence people"
}, {
  BookID: 123,
  BookName: "Seven Habits of most effective people"
}, {
  BookID: 456,
  BookName: "The Tipping point"
}, {
  BookID: 234,
  BookName: "Why Leaders eat last"
}]

Comments

Popular posts from this blog

MySQL 4.1+ using old authentication

When I was working with XAMPP in Ubuntu and asked write PHP script to connect to remote MySQL server which is using PASSWORD hash function to save the password for user, and I found following error. Warning: mysql_connect() [function.mysql-connect]: Premature end of data (mysqlnd_wireprotocol.c:554) in path/to/the/file/where/connection/script/is/written/ Warning: mysql_connect() [function.mysql-connect]: OK packet 1 bytes shorter than expected in path/to/the/file/where/connection/script/is/written/ Warning: mysql_connect() [function.mysql-connect]: mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administration tool to reset your password with the command SET PASSWORD = PASSWORD('your_existing_password'). This will store a new, and more secure, hash value in mysql.user. If this user is used in other scripts executed by PHP 5.2 or earlier you might need to remove the old-passwords flag from your my.cnf file in path/to/the/file/where/conn...

The 7 Types of Leadership: Inspiring Examples and Insights

Leadership is a multifaceted concept with various styles that cater to different needs and situations. Understanding these styles can help you develop your leadership skills and adapt to diverse scenarios. In this article, we'll explore seven prominent leadership styles, each accompanied by insightful examples from influential authors. Let's dive in! Type 1: Transformational Leadership 🚀 Transformational Leadership: Inspiring Change and Innovation Transformational leadership focuses on inspiring and motivating followers to achieve extraordinary outcomes and, in the process, develop their own leadership capacity. Example from Author: James MacGregor Burns James MacGregor Burns, in his book "Leadership," describes transformational leaders as those who seek to change the status quo by appealing to their followers' values and sense of higher purpose. 🔸 Characteristics: - Inspirational Motivation - Intellectual Stimulation - Individualized Consideration - Idealized I...

Security: Password Hashing

In this article I'm going to cover password hashing, a subject which is often poorly understood by newer developers. Recently I've been asked to look at several web applications which all had the same security issue - user profiles stored in a database with plain text passwords. Password hashing is a way of encrypting a password before it's stored so that if your database gets into the wrong hands, the damage is limited. Hashing is nothing new - it's been in use in Unix system password files since long before my time, and quite probably in other systems long before that. In this article I'll explain what a hash is, why you want to use them instead of storing real passwords in your applications, and give you some examples of how to implement password hashing in PHP and MySQL. Foreword As you read on you'll see that I advocate the use of a hashing algorithm called Secure Hashing Algorithm 1 (or SHA-1). Since I wrote this article, a team of researcher...