Sort Array on Key Value
Sorting an array of objects based on a specific key value is a common task in programming. JavaScript provides a built-in method called Array.prototype.sort()
that can be used for this purpose. However, the default behavior of sort()
is to sort the array based on the string representation of the objects, which may not be desirable in many cases.
To sort an array of objects based on a specific key value, you can use a custom comparison function as the argument to sort()
. This function should take two objects as arguments and return a positive number if the first object should come after the second object in the sorted array, a negative number if the first object should come before the second object, or 0 if the objects are equal.
Here is an example of how to sort an array of objects based on the "name"
key using a custom comparison function:
const arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
arr.sort((a, b) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
});
console.log(arr);
This will output the following array:
[
{name:'bob', artist:'rudy'},
{name:'johhny', artist:'drusko'},
{name:'tiff', artist:'needell'},
{name:'top', artist:'gear'}
]
You can also use the sortOn()
method, which is a custom method that can be added to the Array
prototype. This method takes a key value as an argument and sorts the array based on that key.
Here is an example of how to use the sortOn()
method:
Array.prototype.sortOn = function(key) {
this.sort((a, b) => {
if (a[key] < b[key]) {
return -1;
} else if (a[key] > b[key]) {
return 1;
} else {
return 0;
}
});
};
const arr = [{name:'bob', artist:'rudy'},{name:'johhny', artist:'drusko'},{name:'tiff', artist:'needell'},{name:'top', artist:'gear'}];
arr.sortOn("name");
console.log(arr);
This will output the following array:
[
{name:'bob', artist:'rudy'},
{name:'johhny', artist:'drusko'},
{name:'tiff', artist:'needell'},
{name:'top', artist:'gear'}
]
The sortOn()
method can be a convenient way to sort an array of objects based on a specific key value.