IMG-LOGO

How to sort an array of objects in Javascript?

andy - 10 Oct, 2019 2488 Views 0 Comment

In this tutorial we are going to create a prototype method to sort an array of objects in Javascript. We are going to use to a built-in function called sort to order the collection index by comparing one of the property fields of the object.

Let's get started by writing our prototype Sort method.

Array.prototype.sortOn = function (key) {
    this.sort(function (a, b) {
        if (a[key] < b[key]) {
            return -1;
        } else if (a[key] > b[key]) {
            return 1;
        }
        return 0;
    });
}

To test prototype method, we can create an array contains a list of Person object that will have two field properties which will be the FirstName and LastName.

var myArray = [];
myArray.push(
	{
		FirstName: 'Jack',
		LastName: 'Well'
	}
)

myArray.push(
	{
		FirstName: 'Robert',
		LastName: 'William'
	}
)

myArray.push(
	{
		FirstName: 'Anastasia',
		LastName: 'Lee'
	}
)

If we print out the myArray variable. We will have the following array content information.

Let's say we want to sort the array in ascending mode based on the FirstName field. We can use the following Javascript code.

myArray.sortOn("FirstName");

If we view the content of our array variable. It will then be sorted based on the FirstName field.

Here is the full sample code if you want to try it.

<script>
Array.prototype.sortOn = function (key) {
	this.sort(function (a, b) {
		if (a[key] < b[key]) {
			return -1;
		} else if (a[key] > b[key]) {
			return 1;
		}
		return 0;
	});
}

var myArray = [];
myArray.push(
	{
		FirstName: 'Jack',
		LastName: 'Well'
	}
)

myArray.push(
	{
		FirstName: 'Robert',
		LastName: 'William'
	}
)

myArray.push(
	{
		FirstName: 'Anastasia',
		LastName: 'Lee'
	}
)

myArray.sortOn("FirstName");
</script>

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles