Javascript sort array twice [duplicate]

烂漫一生 提交于 2021-01-29 06:12:47

问题


If I have an array of locations like so:

["Roberts", "baltimore", "Maryland", "21212"],
["Adams", "baltimore", "Maryland", "21212"],
["Joes", "philadelphia", "Pennsylvania", "30333"],
["Carls", "new york", "New York", "40415"]

Using Javascript or Jquery, How would I first sort them by state, then by name, so the resulting order would be:

["Adams", "baltimore", "Maryland", "21212"],
["Roberts", "baltimore", "Maryland", "21212"],
["Carls", "new york", "New York", "40415"],
["Joes", "philadelphia", "Pennsylvania", "30333"]

回答1:


If we start with an actual array:

var orig = [
  ["Roberts", "baltimore", "Maryland", "21212"],
  ["Adams", "baltimore", "Maryland", "21212"],
  ["Joes", "philadelphia", "Pennsylvania", "30333"],
  ["Carls", "new york", "New York", "40415"]
];

We can sort it like so:

var sorted = orig.sort(
  function(a, b) {
    // compare states
    if (a[2] < b[2])
      return -1;
    else if (a[2] > b[2])
      return 1;

    // states were equal, try names
    if (a[0] < b[0])
      return -1;
    else if (a[0] > b[0])
      return 1;

    return 0;
  }
);

which returns:

[
  ["Adams","baltimore","Maryland","21212"],
  ["Roberts","baltimore","Maryland","21212"],
  ["Carls","new york","New York","40415"],     
  ["Joes","philadelphia","Pennsylvania","30333"]
]

Example: http://codepen.io/paulroub/pen/ADihk




回答2:


Try this answer (see at the end), but will need an explicit custom criteria:

""" compare(object1, object2)
if object1.state > object2.state then object1 is greater (1)
if object1.state < object2.state then object2 is greater (-1)
if object1.name > object2.name then object1 is greater (1)
if object1.name < object2.name then object2 is greater (-1)
objects are equal or, at least, not sortable by the criteria you exposed.
"""

How to sort an array of objects with jquery or javascript

(note that "array" in array.sort refers your array of objects, and provided your object have actually the field names "name" and "state", since you did not actually specify them - actually they have no fields, so they are not objects nor arrays).



来源:https://stackoverflow.com/questions/21857647/javascript-sort-array-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!