How to sort array formed by objects using .sort ()

2

I have a file that contains the object I want to manipulate. I think two for example. But when in the function of showing ArrayOrdenado () I apply the sort () to order it, being objects and not literals. He does not order me. My idea is that they are ordered by the name parameter of each object that makes up the array. Is it possible?

function Sandskill(nom, edad, especialidad, comp) {
  this.nombre = nom;
  this.edad = edad;
  if (especialidad == 1 || especialidad == 2 || especialidad == 3) {
    if (especialidad == 1)
      this.especialidad = "sistemas";
    if (especialidad == 2)
      this.especialidad = "web";
    if (especialidad == 3)
      this.especialidad = "multiplataforma";
  } else {
    this.especialidad = null;
  }
  this.comp = comp;

  //GETTER
  this.getNom = function() {
    return this.nombre;
  }
  this.getEdad = function() {
    return this.edad;
  }
  this.getEspecialidad = function() {
    return this.especialidad;
  }
  this.getComp = function() {
    return this.comp;
  }
}

var s1 = new Sandskill("Pepe", "22", "1");
var s2 = new Sandskill("Juan", "22", "2", s1);

function mostrarArrayOrdenado() {
  sandskillArray.sort();
  for (i = 0; i < sandskillArray.length; i++) {
    alert(sandskillArray[i].getNom() + " * " + sandskillArray[i].getEdad() + " * " + sandskillArray[i].getEspecialidad() + " * ")
  }
}
    
asked by Eduardo 15.11.2017 в 17:16
source

1 answer

1

The sort () method, as you can see on the website of MDN , you can receive as a parameter a comparator function that has the following form:

function compare(a, b) {
  if (a es menor que b según criterio de ordenamiento) {
    return -1;
  }
  if (a es mayor que b según criterio de ordenamiento) {
    return 1;
  }
  // a debe ser igual b
  return 0;
}

In your case, it could be something like:

sandskillArray.sort(function (o1,o2) {
  if (o1.nombre > o2.nombre) { //comparación lexicogŕafica
    return 1;
  } else if (o1.nombre < o2.nombre) {
    return -1;
  } 
  return 0;
});
    
answered by 15.11.2017 / 17:39
source