How to sort an array of objects with array.sort ()

7

How would I specify for the array.sort(); method how is the sort order? For example, I have an array of person objects, and person has name and number I wanted to sort by name. How would I specify this for my sort method?

    
asked by anonymous 12.01.2015 / 19:41

4 answers

12

The sort method accepts as a parameter [optional] a function with two parameters - two objects to be compared by the sorting algorithm. This function should return a negative number if the first object is less than the second, a positive number if the second is smaller than the first, and zero if both are equal.

If you want to compare by the name of the person (which I assume to be a string), one means is to compare these attributes and return the corresponding value:

pessoas.sort(function(a,b) {
    return a.nome < b.nome ? -1 : a.nome > b.nome ? 1 : 0;
});
    
12.01.2015 / 19:49
4

The .sort() method accepts a function. This function will influence the end position through which that same function returns.

function compare(a, b) {
  if (se a fôr menor que b) {
    return -1;
  }
  if (a fôr maior que b) {
    return 1;
  }
  // são idênticos
  return 0;
}

That is, the function accepts two parameters to which are assigned elements of the array to be compared. If the function gives return greater than 0 , then the b element must "move ahead" of the a element.

Example:

[0, 20, 3, 4].sort(function compare(a, b) {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
})
// dá [0, 3, 4, 20]

If we compare the size of strings an example would be:

['muito longo', 'curto', 'médio'].sort(function compare(a, b) {
    if (a.length < b.length) return -1;
    if (a.length > b.length) return 1;
    return 0;
})
// dá ["curto", "médio", "muito longo"]

That is, if you find a feature to compare the array elements you have you can sort it by following this logic.

    
12.01.2015 / 19:53
3

You can do this:

var pessoas = [ 
    { nome: 'Joao', num: 1     },
    { nome: 'Maria', num: 2     },
    { nome: 'Fulano', num: 3    }
    ];

function compare(a,b) {
  if (a.nome < b.nome)
     return -1;
  if (a.nome > b.nome)
    return 1;
  return 0;
}

pessoas.sort(compare);

If you want to sort by another attribute, just modify it in the compare function.

Font

    
12.01.2015 / 19:49
3

The simplest solution is to pass a function to the sort method of the array, manually comparing the properties of the objects that contain the names. sort uses this function to compare pairs of values, and expects it to return 0 to equal or equivalent strings, a positive number if the first value is greater than the second, or a negative number if the second is greater.

var pessoas = [{
    nome: "Mariana"
}, {
    nome: "Maria"
}, {
    nome: "Ana"
}];

pessoas.sort(function(a,b) {
    if(a.nome < b.nome) return -1;
    if(a.nome > b.nome) return 1;
    return 0;
});

But note the limitations of this method:

  • This method is case sensitive ( 'A' < 'a' ). This can be resolved by converting everything to uppercase or lowercase before comparing.
  • This method considers accented characters to be larger than the others (for example, 'Á' > 'z' ). This can be resolved by replacing some characters before comparing.

A better solution to solve the accent problem, assuming that the browsers / operating systems of the person running the script are set to Portuguese:

pessoas.sort(function(a,b) {
    return a.localeCompare(b);
});

Source: Rui Pimentel's Answer a How to sort array of strings disregarding accents? .

This method localeCompare is available in any string, and also accept a second argument that would be the locale string you want to use (for example, "pt-BR" ). But it has compatibility issues, according to MDN.

    
12.01.2015 / 19:49