I have an array of objects:
var array = [(id, name, value),(id, name, value)]; //and so on
How do I get the array to be sorted in ascending order of the atribute name (array[i][1])
?
I've tried to do this: array[i][1].sort()
, but that doesn't work.
Please help me!
Edit: the array can contain more than two objects! It can contain hundreds.
Source: Tips4all
//This will sort your array
ReplyDeletefunction 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]];
ReplyDeletearray.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.
the sort method contains an optional argument to pass a custom compare function.
ReplyDeleteAssuming you wanted an array of arrays:
var arr = [[3, "Mike", 20],[5, "Alex", 15]];
function compareName(a, b)
{
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}
arr.sort(compareName);
Otherwise if you wanted an array of objects, you could do:
function compareName(a, b)
{
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
//objects
ReplyDeletevar array = [{id:'12', name:'Smith', value:1},{id:'13', name:'Jones', value:2}];
array.sort(function(a, b){
var a1= a.name, b1= b.name;
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;
});
Well, it appears that instead of creating a true multidimensional array, you've created an array of (almost) JavaScript Objects. Try defining your arrays like this ->
ReplyDeletevar array = [ [id,name,value], [id,name,value] ]
Hopefully that helps!