How to sort an array of objects with jquery or javascript [duplicate]
Asked Answered
K

6

215

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.

Edit: Why is this question marked as a duplicate, when it was asked 2 years before the "duplicated" question?

Kuwait answered 31/3, 2011 at 17:33 Comment(5)
Do you have a 2 dimensional array or an array of objects? The above looks more like an array of objects to me.Specialism
{id, name, value} is not valid syntaxDeclaratory
@Sime Sorry about the syntax, I didn't remember it at the time.Kuwait
@Chris yeah, when I think about it it is acutally an array of objects. Sorry about that, I'm multitasking here so sometimes I get a little confused.Kuwait
Regarding your question about the duplicate marker: The other question was asked in 2009, see stackoverflow.com/posts/979256/revisions.Davit
P
406
//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);
Pedestrianize answered 31/3, 2011 at 17:38 Comment(7)
This has been known to break under certain browsers. I'm using IE8 for a project, and it doesn't work for this scenario.Southeastward
@PaolodelMundo we have users who use IE 7/8/9. We haven't had any issues with this code. Can you provide more information about your code?Pedestrianize
The only thing I could imagine breaking it is the a.name.toLowerCase(). I'm just going to use jQuery selectors; I'm only sorting short arrays.Cobbs
how would i reverse this sort?Pap
@Pap to reverse the sort with minimal typing, switch the order of the parameters: function SortByName(b, a) {Dodie
What is the reasoning behind using toLowerCase in a sort?Mobile
@Jackson To sort an array while ignoring case.Pedestrianize
A
38
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.

Ami answered 31/3, 2011 at 17:44 Comment(0)
S
30
//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;
});
Suspensor answered 31/3, 2011 at 17:39 Comment(2)
Life-saver! Would there be a way to make the elements dynamic? So ' array.sort(function(a,b,element){ var a1= a.element, b1= b.element; ' and so on...Orvie
See my answer below. You could easily extend this to do what you're asking @SeaBass. You may need to use a[var] syntax for the dynamic argument approach to work, but you don't need to explicitly return 0 as the answers above shows. 2 - 2 = 0. Less code. Same effect.Trapes
T
21
data.sort(function(a,b) 
{
   return a.val - b.val;
});
Trapes answered 20/9, 2013 at 15:16 Comment(0)
F
11

the sort method contains an optional argument to pass a custom compare function.

Assuming 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;
}
Fulcrum answered 31/3, 2011 at 17:42 Comment(0)
B
3

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 ->

var array = [ [id,name,value], [id,name,value] ]

Hopefully that helps!

Bowerman answered 31/3, 2011 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.