Cómo ordenar una matriz de objetos con jquery o javascript [duplicar]


Esta pregunta ya tiene una respuesta aquí:

Tengo una matriz de objetos:

var array = [(id, name, value),(id, name, value)]; //and so on

¿Cómo puedo ordenar el array en orden ascendente del atributo name (array[i][1])?

He intentado hacer esto: array[i][1].sort(), pero eso no funciona.

¡Por favor ayúdame!

Editar: el array puede contener más de dos objetos! Puede contener cientos.

Editar: ¿Por qué esta pregunta está marcada como un duplicado, cuando se hizo 2 años antes de la pregunta "duplicada"?

Author: Karoline Brynildsen, 2011-03-31

6 answers

//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);
 374
Author: Ketan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 17:38:25
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;
    }
});

La función sort toma un argumento adicional, una función que toma dos argumentos. Esta función debe devolver -1, 0 o 1 dependiendo de cuál de los dos argumentos debe venir primero en la ordenación. Más información .

También he corregido un error de sintaxis en su matriz multidimensional.

 35
Author: Håvard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 17:44:58
//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;
});
 26
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-31 05:52:08
data.sort(function(a,b) 
{
   return a.val - b.val;
});
 14
Author: Wes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-20 15:16:22

El método sort contiene un argumento opcional para pasar una función de comparación personalizada.

Suponiendo que usted quería una matriz de matrices:

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

De lo contrario, si desea una matriz de objetos, podría hacer:

function compareName(a, b)
{

  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
}
 11
Author: Mike Lewis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 17:42:06

Bueno, parece que en lugar de crear una verdadera matriz multidimensional, ha creado una matriz de (casi) Objetos JavaScript. Intenta definir tus arrays de esta manera - >

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

Esperemos que eso ayude!

 3
Author: Hacknightly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 17:36:09