0

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"]
livinzlife
  • 863
  • 3
  • 17
  • 33

2 Answers2

4

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

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

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

Community
  • 1
  • 1
Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87