Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
The jQuery array sort() function is used to sorts the elements of the array. This function is a built-in function in jQuery. This function sorts the array of a number, string, and object in ascending and descending order.
//This will sort your array
function SortByName(a, b){
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
array.sort(SortByName);
var array = [[1, "grape", 42], [2, "fruit", 9]];
array.sort(function(a, b)
{
// a and b will here be two objects from the array
// thus a[1] and b[1] will equal the names
// if they are equal, return 0 (no sorting)
if (a[1] == b[1]) { return 0; }
if (a[1] > b[1])
{
// if a should come after b, return 1
return 1;
}
else
{
// if b should come after a, return -1
return -1;
}
});
The sort
function takes an additional argument, a function that takes two arguments. This function should return -1
, 0
or 1
depending on which of the two arguments should come first in the sorting. More info.
I also fixed a syntax error in your multidimensional array.
//objects
var array = [{id:'12', name:'Smith', value:1},{id:'13', name:'Jones', value:2}];
array.sort(function(a, b){
var a1= a.name.toLower(), b1= b.name.toLower();
if(a1== b1) return 0;
return a1> b1? 1: -1;
});
//arrays
var array =[ ['12', ,'Smith',1],['13', 'Jones',2]];
array.sort(function(a, b){
var a1= a[1], b1= b[1];
if(a1== b1) return 0;
return a1> b1? 1: -1;
});
data.sort(function(a,b)
{
return a.val - b.val;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With